The use of Mybatis here is not introduced, do not know how to use friends can click
www.mybatis.org/mybatis-3/z…
This tutorial is very detailed, including XML configuration, mapping, dynamic SQL are introduced, you can learn and use, this series of articles will be more in-depth understanding of MyBatis.
1. Introduction of ORM
Object Relational Mapping (ORM). The main function of ORM is to complete the Mapping between the Object model and Relational model based on the Mapping configuration file.
1.1 Common ORM Frameworks
1.1.1 Hibernate
Hibernate maintains a mapping relationship between a Java class and a database table through hbM. XML mapping file. With Hibernate mapping, Java developers can view the data rows in a database table in the same way they view Java objects. Each corresponds to a Java class.
1.1.2 JPA
JPA(Java Persistence API) is the Persistence specification of EJB 3.0, which can be used as a Persistence specification independently of EJB.
1.1.3 Spring JDBC
Strictly speaking, Spring JDBC is not an ORM framework. It is simply a very thin encapsulation of native JDBC using templates. Using Spring JDBC can help developers prevent the creation of database connection objects, Statement objects, Repetitive code for exception handling and transaction management to improve development efficiency.
1.1.4 MyBatis
MyBatis, like the persistence framework introduced above, can help developers to mask the underlying repetitive native JDBC code. MyBatis maps ResultSet to Java objects through mapping configuration files or corresponding annotations, and its mapping rules can nest other mapping rules and subqueries, so as to achieve complex logic. One-to-one, one-to-many, many-to-many and bidirectional mappings can also be implemented. Much lighter and more controllable than Hibemate.
2. Overall architecture of MyBatis
MyBatis is divided into three layers, namely basic support layer, core processing layer and interface layer, as shown in the figure
2.1 Basic support layer
The basic support layer contains the whole basic modules of MyBatis, which provide good support for the functions of the core processing layer. Each module is briefly described below.
2.1.1 Data source module
Data source is one of the commonly used components in actual development. Now open source data source provides rich functions, such as connection pool function, link status detection, etc. It is very important to select the data source component with excellent performance to improve the performance of ORM framework and even the whole application. MyBatis itself provides the corresponding data source implementation. Of course, MyBatis also provides the interface to integrate with the third-party interface data source. These functions are located in the data source module.
2.1.2 Transaction management module
MyBatis abstracts transactions in the database and provides the corresponding transaction interface and simple implementation. In many scenarios, MyBatis will be integrated with the Spring framework and the Spring framework will manage the transaction related configuration.
2.1.3 Cache module
When optimizing system performance, optimizing database performance is a very important link, and adding cache is one of the most effective means to optimize database. The proper use of caching can intercept a portion of the database requests in the cache layer, which can reduce the pressure on a significant portion of the database.
MyBatis provides level 1 cache and level 2 cache, and these two levels of cache are both dependent on the implementation of the cache module in the basic support layer. It should be noted that the two levels of cache in MyBatis and the whole application run in a JVM and share a heap memory. If the data volume in the two levels of cache is large, Therefore, if you need to cache a large amount of data, you are advised to use cache products such as Redis, Mongodb, and Memcache.
2.1.4 Binding module
When SqISession calls the corresponding method to perform database operations, it is necessary to specify the SQL node defined in the mapping file. If there is a spelling error, we can only find the corresponding exception at runtime. In order to find such errors as early as possible, MyBatis associates the user-defined Mapper interface with the mapping configuration file through the Binding module. The system can complete the database operation by calling the method in the user-defined Mapper interface to execute the corresponding SQL statement, thus avoiding the above problems. It is worth noting that developers do not need to write a custom Mapper interface implementation, MyBatis will automatically create dynamic proxy objects for it. In some scenarios, the custom Mapper interface can completely replace the mapping configuration file, but some mapping rules and SQL statement definitions are more convenient to write in the mapping configuration file, such as the definition of dynamic SQL statements.
2.1.5 Reflection Module
Reflection in Java is powerful, but writing quality reflection code is a challenge for most developers. MyBatis specifically provides reflection module, which makes a series of optimizations to reflection native to Java, such as caching class metadata, improving reflection performance.
2.1.6 Type conversion module
MyBatis provides an alias mechanism to simplify configuration files, which is one of the main functions of the type conversion module. Another function of the type conversion module is to convert JDBC types to Java types, which is involved in binding arguments to SQL statements and mapping query result sets. Data is converted from Java type to JDBC type when arguments are bound to SQL statements. When the result set is mapped, data is converted from the JDBC type to the Java type.
2.1.7 Log module
Whether in a development test environment or in an online production environment, logging is very important in the overall system. Good logging helps developers and testers quickly locate Bug codes, and O&M engineers quickly locate performance bottlenecks. There are many excellent logging frameworks in the Java world today, such as Log4j, Log4j2, SLF4J, and so on. As a well-designed framework, MyBatis can not only provide detailed log output information, but also integrate various log frameworks. One of the main functions of its log module is to integrate third-party log frameworks.
2.1.8 Resource Loading module
The resource loading module mainly encapsulates the class loader, determines the use sequence of classes, and provides the function of loading class files and other resource files.
2.1.9 Parser module
The parser module mainly provides two functions: one is to encapsulate XPath and provide support for parsing MyBatis -config. XML configuration file and mapping configuration file during initialization of MyBatis; Another feature is support for handling placeholders in dynamic SQL statements.
2.2 Core processing layer
The core processing process of MyBatis is realized in the core processing layer of MyBatis, including the initialization of MyBatis and the whole process of completing a database operation, which are realized based on the basic support layer.
2.2.1 Configuration Resolution
During the initialization of MyBatis, the MyBatis -config. XML Configuration file, mapping Configuration file, and annotation information in Mapper interface will be loaded. The parsed Configuration information will form corresponding objects and be saved in the Configuration object. For example, nodes (that is, mapping rules of a ResultSet) are resolved into a ResultMap object, and defined nodes (that is, attribute mapping) are resolved into a ResultMapping object. Then, use this Configuration object to create the SqlSessionFactor object. After MyBatis is initialized, developers can initialize SqlSessionFactory to create SqlSession objects and complete database operations.
2.2.2 Parameter Mapping -SQL Parsing
Piecing together SQL statement is a tedious and errprone process, in order to release the developers from this boring work, MyBatis to achieve the function of dynamic SQL statement, provides a variety of dynamic SQL statement corresponding node, for example, node, node, node, etc.. By combining these nodes, developers can write dynamic SQL statements that meet almost all requirements. The Scripting module in MyBatis parses the dynamic SQL nodes defined in the mapping file and forms database executable SQL statements based on the arguments passed in by the user. Placeholders in the SQL statement are then processed, binding the arguments passed in by the user.
2.2.3 SQL execution
The execution of SQL statements involves several components, of which the most important are Executor, StatementHandler, ParameterHandler, and ResultSetHandler. Executor maintains level 1 and level 2 caches and provides transaction management, delegating database-related operations to StatementHandler. The StatementHandler uses ParamHandler to bind the arguments of the SQL Statement. The StatementHandler uses the java.sql.Statement object to execute the SQL Statement and obtain the result set. Finally, the StatementHandler uses the ResultSetHandler to map the result set. Get the result object and return. The following figure shows the execution process of an SQL:
2.2.4 plug-in
Although Mybatis has powerful functions, it cannot perfectly fit all application scenarios. Therefore, Mybatis provides a plug-in interface. We can expand Mybatis by adding user-defined plug-ins. User custom plug-ins can also change the default behavior of Mybatis, for example, we can intercept SQL statements and rewrite them. Since the user-defined plug-in will affect the core behavior of MyBatis, before using the customized plug-in, developers need to understand the internal principle of MyBatis, so as to write a safe and efficient plug-in.
3.MyBatis core class introduction
SqlSession, as the main top-level API of MyBatis work, represents the session that interacts with the database, completes the necessary function of adding, deleting, changing and querying the database Executor MyBatis Executor, is the core of MyBatis scheduling. SQL Statement generation and query cache maintenance StatementHandler encapsulates JDBC Statement operations, such as setting parameters and converting the Statement result set to a List. ParameterHandler converts user-passed parameters into parameters required by JDBC Statements. ResultSetHandler converts JDBC returned ResultSet objects into lists. TypeHandler is responsible for the Java data types and JDBC data type mapping and transformation between MappedStatement MappedStatement maintains a < select | update | delete | insert > node encapsulation, SqlSource is responsible for dynamically generating SQL statements based on the parameterObject passed by the user, encapsulating the information into BoundSql objects. BoundSql is BoundSql, indicating dynamically generated SQL statements and corresponding parameter information. Configuration MyBatis All Configuration information is maintained in the Configuration object.Copy the code