From jdbc to mybatis
I have already written several articles to introduce the usage of mybatis. Now I want to analyze the principle of mybatis. This article will explain the process from JDBC to mybatis.
JDBC Query
To query a database using jdbc, follow these seven steps:
1. Load the database driver
2. Get database connection
3. Create a Statement object
4. input parameters
5. Execute SQL statements
6. process query results
7. release resources
Public class JDBC {public static List
> QueryForList () {Connection connection = null; ResultSet rs = null; PreparedStatement pst = null; List
> ResultList = new ArrayList
> (); Try {// 1. load the JDBC Driver Class. forName ("oracle. jdbc. driver. oracleDriver "). newInstance (); String url = "jdbc: oracle: thin: @ localhost: 1521: ORACLEDB"; String user = "root"; String password = "root"; // 2. obtain the database connection = DriverManager. getConnection (url, user, password); // 3. create a Statement object (each Statement is a database execution request) pst = connection. prepareStatement ("select * from userinfo where user_id =? "); // 4. set the input parameter pst. setString (1, "zhangsan"); // 5. execute the SQL statement rs = pst.exe cuteQuery (); // 6. process query results (convert query results to List
Format) ResultSetMetaData rsmd = rs. getMetaData (); int num = rsmd. getColumnCount (); while (rs. next () {Map
Map = new HashMap
(); For (int I = 0; I <num; I ++) {String columnName = rsmd. getColumnName (I + 1); map. put (columnName, rs. getString (columnName);} resultList. add (map) ;}} catch (Exception e) {e. printStackTrace ();} finally {try {// 7. release resource if (rs! = Null) {rs. close (); // close result set rs = null;} if (pst! = Null) {pst. close (); pst = null; // close the execution object} if (connection! = Null) {connection. close (); // close connection = null ;}} catch (SQLException e) {e. printStackTrace () ;}} return resultList ;}}
Optimization process
The above shows that there are seven steps to query using JDBC. Which steps can be further encapsulated and reduce the amount of code we develop?
Step 1 Optimization: Connection acquisition and release
Problem description:Frequent enabling and disabling of database connections results in a waste of resources and affects system performance.
Solution:We can use the database connection pool to solve the problem of resource waste when the database connection is obtained or closed. The connection pool can be used repeatedly to access the database through established connections. Reduce the time for enabling and disabling connections.
Problem description:However, the connection pool is diverse and may change. DBCP connection pool may be used, or C3P0 database connection pool may be used.
Solution:We can perform isolation and decoupling through DataSource. We obtain database connections from DataSource in a unified manner. DataSource can be implemented either by DBCP or by C3P0, therefore, the specific implementation of DataSource should be changed through user configuration.
Step 2 optimization: Unified SQL access
Problem description:When we use JDBC to operate the database, SQL statements are basically scattered in various JAVA classes, so there are three shortcomings:
First, poor readability is not conducive to maintenance and performance tuning.
Second, you need to re-compile and package and deploy the modified Java code.
Third, it is not conducive to SQL extraction and execution on the database client (the middle Java code has to be deleted after the removal, and the prepared SQL statements have to be pieced together in Java after being written ).
Solution:We can consider not writing SQL statements into Java code. Where can we place SQL statements? First, we need to store these SQL statements in a unified manner and put them in the configuration file. Then, obtain the corresponding SQL statement using the key value of the SQL statement.
Step 3 optimization: input parameter ing and dynamic SQL
Problem description:In many cases, you can set placeholders in SQL statements to use input parameters. This method has some limitations. It passes parameters in a certain order, it must match the placeholder one by one. However, if the input parameters are uncertain (for example, for list query, the input query parameters are also different based on the query conditions entered by the user, sometimes it is a parameter, sometimes it may be three parameters), then we have to splice the corresponding SQL statement in the background code based on the input parameters of the request, in this case, the fate of writing SQL statements in Java code cannot be avoided. Since we have stored SQL statements in the configuration file or database, how can we dynamically generate corresponding SQL statements based on the parameters passed in at the front end?
Solution:First, we should solve this dynamic problem first. According to the normal thinking, we use such judgments as if and else. At this time, we thought of Can such labels be introduced into SQL statements? If yes, we need a dedicated SQL parser to parse such SQL statements. However, where does the if variable come from? The input value itself is variable. Therefore, we need to define a variable name that remains unchanged for this value, and the variable name must correspond to the corresponding value, you can find the corresponding value through the variable name. In this case, we think of the Map of key-value. It is determined based on the specific value of the variable name during parsing. If we can determine that there is no problem, if the result is true, then we need to output the SQL segment in the tag. But how can we solve the problem of using the variable name in the tag? Here we need to use a syntax different from SQL to embed variables (for example, using # variable name #). In this way, after the SQL statement is parsed, it can dynamically generate an SQL statement that conforms to the context.
Also, how can we separate placeholder variables and non-placeholder variables? Sometimes we cannot use placeholders alone. placeholders can only be used for query conditions, but cannot be used elsewhere in SQL statements. Here we can use # variable name # To represent placeholder variables, and $ variable name $ to represent non-placeholder variables.
Step 4 optimization: Result ing and result caching
Problem description:It is a complete set of options to execute SQL statements, obtain execution results, convert execution results, and release related resources. If the query statement is executed, a ResultSet result set is returned after the SQL statement is executed. In this case, we need to extract the data of the ResultSet object, otherwise, these results will not be available when resources are released. We can see from the previous optimization that we have encapsulated the methods of getting connections, setting input parameters, executing SQL statements, and releasing resources. Only the result processing is not encapsulated yet, if it can be encapsulated, each database operation does not need to write a lot of Java code by itself. You can simply call an encapsulated method.
Solution:Let's analyze the processing of the execution results, which may be returned directly without any processing, it is also possible to convert the results into a JavaBean object to return, a Map to return, a List to return, and so on. The results may be processed in a variety of ways. From this point of view, we must tell the SQL processor two points: first, what type of objects to be returned; second, how to map the data structure of the objects to be returned to the execution result, in this way, the specific value can be copied to the corresponding data structure.
Next, we can further consider caching SQL Execution results to improve performance. Cache data is in the key-value format. How can this key come from? How can we ensure uniqueness? Even if the same SQL statement is accessed several times, the SQL statement is executed differently due to different input parameters. The cache is many-to-many. However, the SQL statement and the input parameter can be combined as the key value of the data cache.
Step 5 optimization: Solve the Problem of repeated SQL statements
Problem description:Since we put all SQL statements in the configuration file, there will be a duplicate SQL statement at this time. In fact, there are similar SQL statements for several functions, some may be the difference behind the SELECT statement, and some may be the difference between WHERE statements. Sometimes the table structure is changed, so we need to change multiple places, which is not conducive to maintenance.
Solution:What should we do when repeated code occurs in our code program? The repeated code is extracted to become an independent class, and then referenced in each desired place. We can also use this method to solve the SQL repetition problem. By modularizing the SQL segment, we can separate the duplicate SQL segment into an SQL block, then, duplicate SQL blocks are referenced in each SQL statement, so that you only need to modify one block.
Optimization Summary
To sum up the optimization and encapsulation of JDBC:
(1) use the database connection pool to manage connections
(2) SQL statements are stored in the configuration file.
(3) ing between SQL statement variables and input parameters and dynamic SQL statements
(4) Handling of dynamic SQL statements
(5) database operation result ing and result caching
(6) SQL statement repetition
Original article: http://chenjc-it.iteye.com/blog/1455688