MyBatis overall architecture and source code analysis

Introduction to this article

 [General] Briefly describe the three-tier architecture of MyBatis and the core functions of each module, from the basic support layer to the core processing layer, and then to the interface layer exposed to calls.

[Divided] Then analyze in depth, the use of n design patterns in MyBatis; MyBatis working principle and operation process; dynamic SQL statement parsing; mapping mechanism; primary and secondary cache;

1. Analysis of the overall architecture of MyBatis

The MyBatis architecture diagram is mainly divided into three layers. Basic support layer: Responsible for the most basic functional support, including connection management, transaction management, configuration loading, and cache processing . These are common things, and they are extracted as the most basic components. Provide the most basic support for the upper data processing layer. Data processing layer: responsible for specific SQL lookup, SQL parsing, SQL execution and execution result mapping processing   , etc. Its main purpose is to complete a database operation according to the call request. API interface layer: the interface API provided for external use , and developers use these local APIs to manipulate the database. Once the interface layer receives the call request, it will call the data processing layer to complete the specific data processing.

The following is a brief description of the basic support layer, data processing layer, and API interface layer:

1. Basic support layer

According to these single capabilities, the MyBatis basic support layer  can be divided into nine basic modules as shown in the figure above.

        The first one, the type conversion module. Define an alias for a class through the <typeAliase> tag in the mybatis-config.xml configuration file. The " alias mechanism " used here is implemented by the type conversion module in the MyBatis basic support layer. The type conversion module also realizes the mutual conversion between JDBC type and Java type in MyBatis . In the scenario where the SQL template binding user passes in actual parameters, the type conversion module will convert Java type data into JDBC type data; When mapping to result objects, the type conversion module will convert JDBC type data into Java type data.

The second one is the logging module. MyBatis provides a log module to integrate third-party log frameworks in the Java ecosystem. This module can currently integrate excellent log frameworks such as Log4j, Log4j2, and slf4j. The third one is the reflection tool module. The reflection toolbox of MyBatis is a layer of encapsulation based on Java reflection, providing a more flexible and convenient API interface for upper-layer users. Fourth, the Binding module. MyBatis does not need to write the specific implementation of the Mapper interface, but uses the Binding module to automatically generate the dynamic proxy object of the Mapper interface. Fifth, the data source module. MyBatis itself provides a data source implementation, which is also the default implementation of MyBatis. Sixth, the cache module. MyBatis provides a first-level cache and a second-level cache here. Seventh, the parser module. There are two major configuration files in MyBatis that need to be parsed, one is the mybatis-config.xml configuration file, and the other is the Mapper.xml configuration file. These two files are parsed by the parser module of MyBatis, which mainly relies on XPath to realize efficient parsing of XML configuration files and various expressions. The eighth, transaction management module. MyBatis implements a simple layer of abstraction for transactions in the database, providing an easy-to-use transaction interface and implementation. In general, Java projects will integrate Spring, and the Spring framework will manage the transaction. Ninth, resource loading module. The Resources tool class is provided, which internally encapsulates the static fields of the ClassLoaderWrapper class. The methods provided by Resources are all implemented in the ClassLoaderWrapper object. Used to load configuration files.

2. Core processing layer

The core processing layer is the core implementation of MyBatis, which involves the initialization of MyBatis and the whole process of executing a SQL statement .

The first one, configuration parsing. MyBatis has three places where configuration information can be added, namely: mybatis-config.xml configuration file, Mapper.xml configuration file, and annotation information in the Mapper interface. During the initialization process of MyBatis, the configuration information will be loaded, and the configuration object obtained after parsing will be saved in the Configuration object. For example, the <resultMap> tag used (that is, the custom query result set mapping rules) will be parsed into a ResultMap object. We can use the obtained Configuration object to create a SqlSessionFactory object (that is, a factory object for creating a SqlSession object), and then create a SqlSession object to perform database operations.

The second one is SQL parsing and scripting module. The dynamic SQL tags provided by MyBatis are very rich, including <where> tags, <if> tags, <foreach> tags, <set> tags, etc. The scripting module in MyBatis is responsible for dynamically generating the core module of SQL. According to the actual parameters passed in by the user at runtime, the tags in the dynamic SQL will be parsed to form a SQL template, and then the placeholders in the SQL template will be processed, and the placeholders will be filled with the actual parameters at runtime to obtain the real executable database. SQL statement.

The third, SQL execution. In MyBatis, to execute a SQL statement, many components are involved. The core ones are: Executor, StatementHandler, ParameterHandler and ResultSetHandler. Among them, the Executor will call the transaction management module to realize the relevant control of the transaction, and will manage the first-level cache and the second-level cache through the cache module. The real execution of the SQL statement will be realized by StatementHandler . StatementHandler will first rely on ParameterHandler to bind the actual parameters of the SQL template, and then the java.sql.Statement object will pass the SQL statement and the bound actual parameters to the database for execution, and get the ResultSet from the database. Finally, the ResultSetHandler will use the ResultSet Mapped into a Java object and returned to the caller, this is the core of the SQL execution module.

3. Interface layer

The interface layer is a collection of interfaces that MyBatis exposes to calls, such as SqlSession interface, SqlSessionFactory interface, etc. Among them, the core is the SqlSession interface to obtain the Mapper proxy, execute SQL statements, control transaction switches, and so on.

At this point, we have explained the three-tier architecture of MyBatis and the core functions of each module in it. The design pattern and the startup process of MyBatis can be expanded below.

2. The use of design patterns in MyBatis

The overall architecture         of MyBatis conforms to the Facade Pattern . The log module is a typical scene using the adapter pattern. The adapter pattern (Adapter Pattern) is used as a bridge between two incompatible interfaces, converting the interface of a class into another interface that the customer wants. The adapter mode enables those classes that could not work together due to incompatible interfaces to work together; when loading log components first, and when implementing plug-ins , use dynamic proxy (Proxy Pattern) to provide a proxy object for the target object and be controlled by the proxy object The reference to the target object; the data source module focuses on the creation of data sources and the source code analysis of the database connection pool; the creation of data sources is more complicated, and the factory pattern (Factory Pattern) is used for the creation of complex objects ; the processing of dynamic SQL statements in MyBatis At this time, the dynamic SQL label will be parsed into SqlNode objects, and multiple SqlNode objects form a tree structure through the Composite Pattern for use by the upper layer. The MyBatis cache module is a classic decorator pattern (Decorator Pattern)The implemented module, the class diagram is as follows: Cache interface is the core interface of the cache module, which defines the basic operations of the cache; PerpetualCache plays the role of ConcreteComponent in the cache module, and uses HashMap to implement cache-related operations; BlockingCache: the blocking version of the cache decorator , to ensure that only one thread goes to the database to find the data corresponding to the specified key. The cache module is as shown in the figure below

As shown in the figure below, the builder pattern (Builder Pattern) is widely used in the configuration loading phase to use multiple simple objects to build a complex object step by step. BaseBuilder: the parent class of all parsers, including configuration file instances, a common method for parsing files; XMLConfigBuilder: mainly responsible for parsing mybatis-config.xml; XMLMapperBuilder: mainly responsible for parsing the mapping configuration Mapper.xml file; XMLStatementBuilder: mainly responsible for Parse the SQL nodes in the mapping configuration file;

SqlSessionFactory uses the factory pattern (Factory Pattern) to create SqlSession, its default implementation class DefaultSqlSessionFactory, which obtains the core method openSessionFromDataSource() of SqlSession, and the TransactionFactory obtained from configuration in this method is a typical application of Strategy . During runtime, the implementation of the TransactionFactory interface is determined by the configuration of the configuration file. The configurable options include: JDBC, Managed, and the implementation of TransactionFactory can be flexibly replaced according to requirements; Executor is as shown in the figure below: it defines the most basic method of database operation;         CacheingExecutor  : Using the Decorator Pattern, which enhances the ability of the second-level cache for the Executor that actually provides database queries; the location of the second-level cache initialization: DefaultSqlSessionFactory.openSessionFromDataSource(); BaseExecutor: an abstract class that implements most of the methods of the executor interface, mainly providing cache management and transaction management The abstract methods that other subclasses need to implement are: doUpdate, doQuery and other methods; BatchExecutor: execute all update statements in batches, and implement batch processing based on the batch operation of jdbc; SimpleExecutor: the default executor, which creates a statement every time it is executed. Close after use. ;ReuseExecutor: reusable executor, store the statement in the map, operate the statement in the map without repeatedly creating the statement;         BaseExecutor and BaseStatementHandler are the template pattern (Template Pattern) ; Some methods mainly provide cache management and transaction management capabilities. The abstract methods that other subclasses need to implement are: doUpdate, doQuery and other methods;

3. MyBatis working principle (running process)

[General] The operation process of MyBatis can be divided into three stages: 1. Initialization stage: read the configuration information in XML configuration files and annotations, create configuration objects, and complete the initialization of each module; 2. Proxy encapsulation stage : Encapsulate the programming model of iBatis, and use the mapper interface to develop the initialization work; 3. Data access phase: complete the SQL analysis, parameter mapping, SQL execution, and result analysis process through SqlSession;

(1) Read the MyBatis configuration file: mybatis-config.xml is the global configuration file of MyBatis, which configures information such as the operating environment of MyBatis, such as database connection information.  

(2) Load the mapping file. The mapping file is the SQL mapping file, which configures the SQL statements for operating the database and needs to be loaded in the MyBatis configuration file mybatis-config.xml. The mybatis-config.xml file can load multiple mapping files, and each file corresponds to a table in the database.

(3) Construct a session factory: Construct a session factory SqlSessionFactory through MyBatis environment and other configuration information.

(4) Create a session object: Create a SqlSession object by the session factory, which contains all the methods for executing SQL statements.        

(5) Executor: The bottom layer of MyBatis defines an Executor interface to operate the database. It will dynamically generate SQL statements to be executed according to the parameters passed by SqlSession, and is responsible for maintaining the query cache.        

(6) MappedStatement object: There is a parameter of MappedStatement type in the execution method of the Executor interface, which encapsulates the mapping information and is used to store the id, parameters and other information of the SQL statement to be mapped.        

(7) Input parameter mapping: The input parameter type can be collection types such as Map and List, or basic data types and POJO types. The input parameter mapping process is similar to JDBC's process of setting parameters for preparedStatement objects.        

(8) Output result mapping: The output result type can be collection types such as Map and List, or basic data types and POJO types. The output result mapping process is similar to the JDBC parsing process for the result set.

Summarize

Briefly describe the three-layer architecture of MyBatis and the core functions of each module in it, from the basic support layer to the core processing layer, and then to the interface layer exposed to calls. Then analyze in depth, the use of n design patterns in MyBatis; MyBatis working principle and operation process; dynamic SQL statement parsing; mapping mechanism; primary and secondary cache;

Guess you like

Origin blog.csdn.net/Park33/article/details/129934254