One, foreword

After polishing the Spring framework, we move on to the next journey, Mybatis. Compared to Spring, Mybatis is short and dapper. Before this series of source code begins, we will first understand the relevant knowledge points of Mybatis.

What is MyBatis?

MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures, and advanced mapping. MyBatis avoids almost all of the JDBC code and manual setting of parameters and fetching result sets. MyBatis can configure and map native information using simple XML or annotations to map interfaces and Java’s POJOs(Plain Old Java Objects) to records in the database.

Three, architecture,

1. Interface layer

The interface layer mainly defines how to interact with the database. In Mybatis, there are two ways to interact.

  • API provided by Mybatis

The Statement Id and parameters are used to operate the database by obtaining the SqlSession object using the Mybatis API.

String statement = "com.viewscenes.netsupervisor.dao.UserMapper.getUserList";
List<User> result = sqlsession.selectList(statement);
Copy the code
  • Use the Mapper interface

In fact, that’s the way it’s often done, programming to the interface. Methods in each Mapper interfaces corresponds to the Mapper. The XML files a select/insert/update/delete node. The ID in the node is the name of the method in the interface, which can be called directly when used. However, it is worth noting that it ultimately executes sqlsession.select (), sqlsession.delete ().

2. Data processing layer

This is the heart of Mybatis. It is responsible for parameter mapping and dynamic SQL generation, after which Mybatis executes SQL statements and maps the returned results to custom types. For parameter mapping and result set transformation, we rely primarily on typeHandlers. To help you understand, let’s look at a few types of processors.

Type processor Java type The JDBC type
StringTypeHandler java.lang.String CHAR, VARCHAR
DateTypeHandler java.util.Date TIMESTAMP
BooleanTypeHandler java.lang.Boolean, boolean BOOLEAN for database compatibility
IntegerTypeHandler java.lang.Integer, int Database compatible with NUMERIC or INTEGER

3. Frame support layer

  • Transaction management

Transaction management is an essential part of the ORM framework. However, in general, Mybatis is used with Spring to take over transaction management.

  • The connection pool

We cannot create a connection to a database every time we execute SQL. Since creating a connection is a relatively time-consuming operation, the common practice is to keep a list of N pre-created connections, grab them when they are needed, and return them when they are finished. There are many open source implementations of database connection pooling in the industry. For example, C3P0, DBCP, Tomcat Jdbc Pool, BoneCP, and Druid.

  • The cache

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.

Level 1 cache is the CACHE of SqlSession level. When the same SQL statement is executed twice in the same SqlSession, the data queried in the database will be written to the cache (memory) after the first execution, and the data will be obtained from the cache and will not be queried from the database for the second time, thus improving the query efficiency. Mybtais enables level 1 caching by default.

Level 2 cache is mapper level cache, multiple SQLSessions to operate the same MAPper SQL statement, multiple SQLsessions to operate the database data will exist level 2 cache area, multiple SQLsessions can share level 2 cache, level 2 cache is cross-SQLSESSION. To enable level 2 caching, add a line: to your SQL mapping file. It caches all select statements, flusher the cache during INSERT, UPDATE, and DELETE statements, and reclaims the cache according to the LRU algorithm.

4. SQL configuration

Most of the time we configure SQL using XML, but Mybatis also supports annotations, as shown below.

@Select({"<script>"."select * from user"
		"</script>"})
List<ConsultContent> getUserList();
Copy the code

However, do not recommend this way to do, unless you want to dig…. Imagine a complex SQL, dozens of lines, hundreds of lines, written at a time, maintenance tears.

5. 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.

Four, the main components

  • SqlSession, as the main top-level API of MyBatis, represents the session of interaction with the database, and completes the necessary function of adding, deleting, changing and searching the database.

  • The Executor MyBatis Executor, the core of MyBatis scheduling, is responsible for the generation of SQL statements and the maintenance of the query cache.

  • StatementHandler encapsulates the JDBC Statement operation and performs operations on JDBC Statements, such as setting parameters and converting the Statement result set to a List.

  • ParameterHandler is responsible for converting user-passed parameters into those required for a JDBC Statement.

  • 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.

  • Article MappedStatement MappedStatement maintains a < select | update | delete | insert > node encapsulation.

  • The SqlSource is responsible for dynamically generating SQL statements based on the parameterObject passed by the user, encapsulating the information into BoundSql objects, and returning it.

  • BoundSql indicates dynamically generated SQL statements and parameter information.

  • Configuration MyBatis All the Configuration information is kept in the Configuration object.

Five, version,

The database used in this series is MySQL, Mybatis version 3.4.6. Here are the POM file coordinates.

Mybatis </groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> < the dependency > < groupId > org. Mybatis < / groupId > < artifactId > mybatis - spring < / artifactId > < version > 1.3.2 < / version > </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.6</version> </dependency> <groupId>com.mchange</groupId> <artifactId> c3P0 </artifactId> The < version > 0.9.5.2 < / version > < / dependency >Copy the code