preface

MyBatis design idea – overall architecture

  1. ** Annotatios: ** annotation development module, defines all annotations used in mapper interface, such as @param, @update, @select, @delete, etc.
  2. ** Binding: ** Generates a dynamic proxy class for the Mapper interface and manages its life cycle.
  3. ** Builder: ** Defines all the builders needed internally for MyBatis. Most of the core components of MyBatis are created through the Builder pattern.
  4. ** Cache: **cache function implementation, including a variety of cache decorators, MyBatis level cache, level two cache are based on this module.
  5. ** CURSOR: ** Supports data query by cursor, which is suitable for processing large data query scenarios.
  6. **datasource: ** Datasource module, MyBatis implements its own datasource.
  7. Exceptions: Defines common exceptions.
  8. **executor: the **executor module defines the core process of MyBatis. The main functions include Statement creation, SQL parameter concatenation, SQL Statement execution, result set parsing, etc.
  9. ** IO: ** resource file reading module, used to locate, read MyBatis related configuration information.
  10. ** JDBC: ** provides some JDBC utility classes.
  11. ** this package only has two annotations: @usesJava7 and @usesJava8. These two annotations are used to identify which can use the JDK7 API and which can use the JDK8 API.
  12. ** Logging: the **logging module defines log levels and integrates multiple logging frameworks.
  13. ** Mapping: ** Mainly provides the mapping function between configuration files and entity objects, including Mapper mapping, parameter mapping, and result set mapping.
  14. Parsing: a tool to parse string parsing, such as placeholders like “$” and “#” in SQL statements.
  15. ** Plugin: ** plug-in module, using proxy mode to achieve functional enhancements. The famous paging plug-in PageHelper is based on the Plugin module.
  16. Reflection: a reflection module that encapsulates Java’s underlying reflection mechanism and provides a series of reflection utility classes.
  17. ** Scripting: Dynamic SQL language implementation, configuration file if, WHERE and other SQL tags are implemented in this package.
  18. ** Session: ** core module, to achieve the function of SqlSession.
  19. ** Transaction: **transaction module, which implements the basic functionality of JDBC transactions.
  20. **type: **type handling module, including converters for all database types and corresponding Java types.

MyBatis framework overall design

Interface layer – how to interact with the database

MyBatis interacts with the database in two ways:

  1. Use the API provided by traditional MyBatis;

  2. Use Mapper interface;

1.1. Use API### provided by traditional MyBatis

The Statement Id and query parameters are passed to the SqlSession object. The SqlSession object is used to interact with the database. MyBatis provides a very convenient and simple API for users to realize the operation of adding, deleting, changing and checking data of the database, as well as the maintenance operation of database connection information and MyBatis own configuration information.

Traditional MyBatis working mode

The above method of using MyBatis is to create a SqlSession object to deal with the database, and then operate the database according to the Statement Id and parameters. This method is simple and practical, but it does not conform to the concept of object-oriented language and the programming habit of interface programming. As Interface oriented programming is the general trend of object oriented, in order to adapt to this trend, MyBatis added a second way to support Interface (Interface) call.

1.2. Use Mapper interface

MyBatis abstracts each node in the configuration file into a Mapper interface:

Methods declared in the interface and the node in the < select | update | delete | insert > node corresponding to the < select | update | delete | insert > node id value for the method’s name in the Mapper interfaces, ParameterType indicates the input parameterType of the corresponding method of the Mapper. The resultMap value corresponds to the return value type or element type of the result set represented by the Mapper interface.

Mapping between Mapper interfaces and mapper. XML configuration files

Sqlsession. getMapper(xxxmapper. class) method, MyBatis will generate a Mapper instance by dynamic proxy mechanism according to the method information declared by the corresponding interface. Sqlsession. select(“statementId”,parameterObject); sqlSession. select(“statementId”,parameterObject); Or SqlSession. Update (” statementId parameterObject); And so on to achieve the operation of the database, MyBatis reference Mapper interface this call method, purely to meet the needs of interface programming. (Another reason is that interface-oriented programming allows users to configure SQL statements with annotations on the interface, which allows “0 configuration” out of the XML configuration file.)

2. Data processing layer

The data processing layer can be said to be the core of MyBatis. From a large perspective, it needs to complete two functions:

  1. Build dynamic SQL statements by passing in parameters;

  2. SQL statement execution and encapsulation query results integration List;

2.1 parameter mapping and dynamic SQL statement generation

Dynamic statement generation can be said to be a very elegant design of MyBatis framework. MyBatis uses Ognl to dynamically construct SQL statements by passing in parameter values, which makes MyBatis have strong flexibility and expansibility.

Parameter mapping refers to the conversion between Java data types and JDBC data types: there are two processes: the query phase, where we convert Java data to JDBC data and set the value in preparedStatement.setxxx (); The other is to convert the jdbcType data in the resultset query resultset to Java data types.

2.2. Execute SQL statements and encapsulate query results to integrate List

After the dynamic SQL statement is generated, MyBatis will execute the SQL statement and convert the possible result set to a List List. MyBatis supports one-to-many and many-to-one transformation of result set relation in the processing of result set, and has two support methods, one is the query of nested query statement, and the other is the query of nested result set.

3. Frame support layer

3.1. Transaction management mechanism

Transaction management mechanism is an indispensable part of ORM framework, and the quality of transaction management mechanism is also a criterion to evaluate whether an ORM framework is excellent.

3.2 connection pool management mechanism

Since creating a database connection consumes a lot of resources, the design of connection pool is very important for applications with high data throughput and high traffic volume.

3.3. Caching mechanism

In order to improve the data utilization rate and reduce the pressure on the server and database, MyBatis will provide session-level data cache for some queries. It will place a query into SqlSession. Within the allowed time interval, MyBatis will directly return the cache results to users for identical queries. You don’t have to look it up in the database.

3.4. How to configure SQL statements

The traditional way of MyBatis to configure SQL statements is to use XML files for configuration, but this way cannot support the concept of interface oriented programming. In order to support interface oriented programming, MyBatis introduces the concept of Mapper interface. The introduction of interface oriented makes it possible to configure SQL statements with annotations. Users only need to add necessary annotations to the interface, and there is no need to configure XML files. However, MyBatis only provides limited support for annotation configuration SQL statements, and some advanced functions still rely on XML configuration files to configure SQL statements.

4. Guide layer

The boot layer is the way to configure and launch MyBatis configuration information. MyBatis provides two ways to boot MyBatis: XML configuration file based method and Java API based method.

5. Main components and their relations

The main core components of MyBatis

From the perspective of MyBatis code implementation, the main core components of MyBatis are as follows:

**SqlSession: ** as MyBatis work of the main top-level API, said and database interaction session, complete the necessary database add, delete, change and check function;

**Executor: The **MyBatis Executor is the core of MyBatis scheduling. It is responsible for the generation of SQL statements and the maintenance of the query cache.

**StatementHandler: ** Encapsulates the JDBC Statement operation. It is responsible for performing operations on JDBC Statements, such as setting parameters and converting the Statement result set to a List.

ParameterHandler: ParameterHandler is responsible for converting user-passed parameters to those required for JDBC Statements.

**ResultSetHandler: ** Is responsible for converting the ResultSet object returned by JDBC into a collection of type List;

**TypeHandler: ** Is responsible for mapping and converting between Java and JDBC data types;

MappedStatement: * * * * MappedStatement maintains a < select | update | delete | insert > node encapsulation;

**SqlSource: ** Dynamically generates SQL statements based on the parameterObject passed by the user, encapsulates the information into BoundSql objects, and returns it.

**BoundSql: ** indicates the dynamically generated SQL statement and parameter information.

**Configuration: ** All MyBatis Configuration information is maintained in the Configuration object;

Their relationship is shown below:

That’s the end of the article

Like xiaobian to share technical articles can like attention oh!

Xiaobian here sorted out a mind map of Mybatis, friends who need to know can have a look

As well as collated MyBatis source analysis of more than 300 pages of technical documentation, MyBatis technical principle and combat data collection of more than 200 pages, MyBatis: entry + configuration information + printing + cache + integration of Spring+ interview, these are collated good information. Concern public number: Kylin bug