[MyBatis Series 5] MyBatis4 core objects SqlSessionFactoryBuiler, SqlSessionFactory, SqlSession, Mapper

Preface

In the previous articles, we briefly explained the simple usage of MyBatis, as well as the use of one-to-one, one-to-many and many-to-many related dynamic SQL query tags, and also mentioned that nested queries cause N+1 problems and delayed loading For related functions, this article will start from the implementation of MyBatis's bottom layer to analyze the four core objects of MyBatis.

The four core objects of MyBatis

Let us first recall the steps in the previous article to use MyBatis to complete a database operation, as shown in the following figure: It
Insert picture description here
can be concluded that the main steps are as follows :

  • 1. Load the configuration file
  • 2. Get SqlSessionFactoryBuiler object
  • 3. Obtain the SqlSessionFactory object through SqlSessionFactoryBuiler and configuration file stream
  • 4. Use the SqlSessionFactory object to open a SqlSession
  • 5. Obtain the corresponding Mapper object through SqlSession
  • 6. Call the corresponding interface through the Mapper object to query the database

From these steps, we can see that MyBatic has four core objects to complete a database operation: SqlSessionFactoryBuiler, SqlSessionFactory, SqlSession and Mapper .

SqlSessionFactoryBuiler

The only function of SqlSessionFactoryBuilder is to create SqlSessionFactory, it will not be used after creation, so SqlSessionFactoryBuiler has a very short life cycle.

There are 9 methods provided in SqlSessionFactoryBuiler, all of which return SqlSessionFactory objects.
Insert picture description here
The builder mode is used in SqlSessionFactoryBuiler. If you want to learn about the builder mode, click here .

(2+1) method analysis

Although 9 methods are provided, in fact we can regard them as (2+1) methods.
Please see the picture below. The first three methods eventually call the fourth method, so it is actually one method.
Insert picture description here
Looking at the following is actually the same thing. Three methods eventually call the same method:
Insert picture description here
so these two methods It corresponds to 2 in the 2+1 method.
As you can see in the above figure, these two methods call another method build(Configuration config) at the same time after parsing the configuration file into a Java configuration class Configuration, and this method does nothing but configure The class passed in and returned a DefaultSqlSessionFactory object. This object is the implementation class of SqlSessionFactory.
Insert picture description here
So there is nothing to analyze in 1 in 2+1. Then this 2 actually supports 2 ways to read files. For example, we get a SqlSessionFactory. Objects are most commonly used in the following ways:

String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

But in fact, we can also use the following methods to obtain the SqlSessionFactory object:

Reader reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

The only difference between these two methods is here, the other two parameters are the same.

  • String environment:
    This is actually used to determine which environment to load.
    The figure below is our mybatis file, which defines an environment id. When we need to support multi-ring data source switching, we can define multiple ids, and then input different ids according to different environments.Insert picture description here
  • Properties properties: The properties in the dataSource below us in the above figure are not directly input, but are configured with ${jdbc.driver}, and the values ​​of these properties can be maintained in a properties file separately.
    Insert picture description here
    Then the code can be rewritten like this:
Reader reader = Resources.getResourceAsReader(resource);
        Properties properties = Resources.getResourceAsProperties("db.properties");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader,properties);

After adopting this method, the mybatis-config.xml file can directly use ${} to get the value. Of course, there is actually a simpler way, that is to directly import the properties file in mybatis-config.xml, so that you don't need to parse the properties file in the code:

<properties resource="db.properties"></properties>

Insert picture description here
Many people may not have used this kind of properties file, but this method is still very common when I first started to learn programming.

The function of the build() method is to read the XML file and encapsulate the read information into the Congiguration. As for how to parse the XML file is not the focus of this article, we will not introduce too much.

Through the above analysis, we can also easily know that since it provides a method to directly pass in Congiguration to obtain the SqlSessionFactory object, in fact, we can also directly construct Congiguration directly through Java code instead of using XML format, and then Obtain the SqlSessionFactory object directly. as follows:

Configuration congiguration = new Configuration();
        congiguration.setDatabaseId("xxx");
        congiguration.setCacheEnabled(false);
        SqlSessionFactory sqlSessionFactory1 = new SqlSessionFactoryBuilder().build(congiguration);

Of course, if you want to modify this method, you have to change the code every time, it will be more troublesome, and it does not seem intuitive, so it is recommended to use the xml method to configure the basic properties of MyBatis.

InputStream和Reader

Reader and InputStream are two methods of reading files provided by the I/O library in Java. Reader is used to read 16-bit characters, that is, Unicode-encoded characters; and InputStream is used to read ASCII characters and binary data . Regarding this difference, I will separately summarize the input and output streams in Java. Those who are interested can follow me and pay attention to my blog. I won't expand on these two methods here. What you need to know here is that these are two different input methods.

SqlSessionFactory

SqlSessionFactory is an interface, the default implementation class, mainly used to generate SqlSession objects, and SqlSession objects need to be created constantly, so SqlSessionFactory exists globally, and there is no need to create it repeatedly, so this is a singleton object.

SqlSessionFactory can be easily thought of by its name, and it uses the factory design pattern .

SqlSessionFactory has only two implementation classes: DefaultSqlSessionFactory and SqlSessionManager .

DefaultSqlSessionFactory

DefaultSqlSessionFactory is the default implementation class of SqlSessionFactory, and it is basically used now. This class provides 8 methods to obtain the SqlSession object. This screenshot is not easy to take, for the convenience of comparison, I list the methods:

SqlSession openSession();
SqlSession openSession(boolean autoCommit);
SqlSession openSession(TransactionIsolationLevel level);
SqlSession openSession(ExecutorType execType,TransactionIsolationLevel level);
SqlSession openSession(ExecutorType execType);
SqlSession openSession(ExecutorType execType, boolean autoCommit);
SqlSession openSession(Connection connection);
SqlSession openSession(ExecutorType execType, Connection connection);

The TransactionIsolationLevel and autoCommit of these 8 methods are better understood, that is, the transaction isolation level and whether to enable automatic commit.
The first six methods actually call the openSessionFromDataSource method, and the latter two call the openSessionFromConnection method.
Insert picture description here
Insert picture description here
From the screenshots of the two methods above, it is obvious that the two methods are basically the same. The only difference is that the openSessionFromConnection method is to get the current session from the Connection object whether to enable automatic submission.

Executor

The final execution of SQL statements in MyBatis is achieved through the Executor object. There are only three types of Executor:
SIMPLE , REUSE , and BATCH . The default is the SimpleExecutor actuator corresponding to the SIMPLE type. SimpleExecutor represents a normal executor and will not do any processing. The REUSE type corresponds to the ReuseExecutor executor, which reuses prepared statements. The BATCH type corresponds to the BatchExecutor executor, which is generally used to perform batch operations.
Executor is one of the four major objects belonging to SqlSession. There will be a blog for special analysis later. We will not go into it here for the time being.

SqlSessionManager

SqlSessionManager is actually nothing new, it just puts the responsibilities of SqlSessionFactory and SqlSession together at the same time, so we don't need to discuss this too much.
Insert picture description here

SqlSession

SqlSession is used to manipulate the sql statements we wrote in the xml file. Every time we operate the database, we need a SqlSession object. SqlSession is used to interface with transactions in the database, so SqlSession contains information such as transaction isolation level. of.

SqlSession instance is not thread safe, so the best request scope is request or method.

SqlSession is also an interface, with two implementation classes: DefaultSqlSession and SqlSessionManager .
SqlSessionManager is mentioned above, so I won't repeat it here. Here we can look at the class diagrams of these classes to make it clearer:
Insert picture description here

Mapper

Mapper is an interface without any implementation class. The main function is to map the interface of the Sql statement. The interface instance of the mapper is obtained from the SqlSession object, so the scope of the Mapper instance is the same as or smaller than that of the SqlSession.
The scope of the Mapper instance is best to remain within the scope of the method, otherwise it will be difficult to manage.

The name of the Mapper interface should be the same as the xml file corresponding to the SQL statement, and the method name defined in the Mapper interface corresponds to the statement id in the xml file.

Four major object life cycles

SqlSessionFactoryBuiler only needs to be used when creating a SqlSessionFactory object, and it can be discarded after creation. SqlSessionFactory is globally unique and is a singleton object, but it needs to exist globally. SqlSession generally corresponds to a request, and Mapper is generally controlled in the method.

Object Life cycle
SqlSessionFactoryBuiler Method partial (Method) can be discarded after use
SqlSessionFactory Application level (Application), exists globally, is a singleton object
SqlSession Request or method (Request/Method)
Mapper Method

to sum up

This article mainly analyzes the four core objects in MyBatis: SqlSessionFactoryBuiler, SqlSessionFactory, SqlSession, Mapper. And analyzed the generation process and life cycle of the four major objects from the perspective of source code.
The next article will analyze the execution process of SqlSession. After the analysis, we will understand how our parameters and result sets are mapped.
Please pay attention to me and learn and progress with the lone wolf .

Guess you like

Origin blog.csdn.net/zwx900102/article/details/108581342