mybatis core components of its lifecycle

First, the core components

With a diagram to show the relationship between the Mybatis core components, shown in Figure 1-1

mybatis core components

  1. The SqlSessionFactoryBuilder (builder) : may be constructed from a profile pre-customized XML instance or SqlSessionFactory Configuration of an example, using the stepwise constructed Builder mode . Examples SqlSessionFactory build from very simple XML file, resource files under recommended classpath configuration. It is also possible to use any of the input stream (the InputStream) example, in the form of a string of a file path or file: URL form // file path configurations. MyBatis includes a utility class called Resources, which contains some practical methods, resource files can be loaded from the classpath or other location easier.

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

    XML configuration file contains the settings for MyBatis core system, comprising a database connection instance data source (the DataSource) transactional scope and decisions and transaction manager (the TransactionManager) control method. Here is a simple example:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
      PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
      <environments default="development">
        <environment id="development">
          <transactionManager type="JDBC"/>
          <dataSource type="POOLED">
            <property name="driver" value="${driver}"/>
            <property name="url" value="${url}"/>
            <property name="username" value="${username}"/>
            <property name="password" value="${password}"/>
          </dataSource>
        </environment>
      </environments>
      <mappers>
        <mapper resource="org/mybatis/example/BlogMapper.xml"/>
      </mappers>
    </configuration>
    
  2. A SqlSessionFactory (factory interface) : rely on it to generate SqlSession, use the factory mode .

  3. SqlSession (session) : SqlSession completely contains all methods needed for the database to execute SQL commands. You can directly execute SQL statement has been mapped by SqlSession instance. E.g:

    try (SqlSession session = sqlSessionFactory.openSession()) {
    	Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
    }
    

    Now, with a more concise way - the correct description of the parameters of each statement and returns the value of the interface (such as BlogMapper.class), you can now not only perform more clearly and type-safe code, but also do not worry about error-prone the string literals and casts. It can improve the readability and maintainability of the code.

    try (SqlSession session = sqlSessionFactory.openSession()) {
    	BlogMapper mapper = session.getMapper(BlogMapper.class);
    	Blog blog = mapper.selectBlog(101);
    }
    
    package org.mybatis.example;
    public interface BlogMapper {
      Blog selectBlog(int id);
    }
    
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
      PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="org.mybatis.example.BlogMapper">
      <select id="selectBlog" resultType="Blog">
        select * from Blog where id = #{id}
      </select>
    </mapper>
    
  4. SQL Mapper (mapper) : He has a Java interface and an XML file (or notes), and need to give the corresponding SQL and mapping rules. He is responsible for sending SQL to perform, and returns the result.

Second, the scope (Scope) and life cycle

Life cycle is an important component in question, especially in a multi-threaded environment, such as Internet applications, Socket request, etc., but Mybatis also used in a multithreaded environment, improper use can cause serious multithreading issues, in order to correct write Mybatis applications, we need to know the life cycle Mybatis components.

Lifecycle mybatis assembly 1-2 shown in FIG.

Here Insert Picture Description

1.SqlSessionFactoryBuilder
This class can be instantiated, and disposal, SqlSessionFactory once created, it is no longer needed. Thus the scope SqlSessionFactoryBuilder preferred example is a method for the scope (i.e. bureau portion Method variables ). You can reuse SqlSessionFactoryBuilder SqlSessionFactory to create multiple instances, but it is best not to have been allowed to exist, to ensure that all of the XML parsing resources can be freed to more important things.
2.SqlSessionFactory
SqlSessionFactory can be thought of as a database connection pool, its role is to create SqlSession interface object . Because the essence of MyBatis is Java operation of the database, so SqlSessionFactory once created should have been present during the execution of the application, there is no reason to discard it or re-create another instance. The best practice is to use SqlSessionFactory during application runtime do not create duplicate many times rebuilt many times SqlSessionFactory be seen as a code for "bad taste (bad smell)". So SqlSessionFactory of the best scope is the scope of application . There are many ways to do this, the easiest is to use the Singleton pattern or Static Singleton pattern .
3.SqlSession
If SqlSessionFactory equivalent database connection pool, then SqlSession is equivalent to a database connection (Connection objects). Each thread should have its own SqlSession instance. Examples of SqlSession not thread-safe, thus can not be shared, so it is best request or method scope scope. Never keep references to SqlSession instance of a static field in class, or even a class instance variables does not work. Never keep references to a SqlSession hosted in any type of scope, such as Servlet framework HttpSession. If you are currently using one Web framework, to consider the SqlSession HTTP request and a similar object scope . In other words, HTTP requests received each time, one can open the SqlSession, returns a response, it is closed. The closing operation is very important, you should put this in close operation in the finally block to ensure that every time a shutdown. The following example is a standard mode to ensure SqlSession closed:

try (SqlSession session = sqlSessionFactory.openSession()) {
  // 你的应用逻辑代码
}

Extended: above this application is called "try-with-source", isjdk7.0After the new method will create the object's handle external resources in a try keywords in brackets after it, when the try-catch block is finished, Java will ensure that external resources close method is called. New features try-with-resource is not a JVM virtual machine, but implements a JDKSyntactic sugarWhen you found the above code will be decompiled, in fact, JVM virtual machine is concerned, it is still seen before writing. ,

4.Mapper
mapper is some binding statement of your mapping interface created by you. Examples mapper interface is obtained from the SqlSession. Thus Technically speaking, any mapper instance the maximum request and the scope thereof is SqlSession same. Nevertheless, the best example of the scope is a method mapper scope . That is, the request should be mapped in the instance method invocation thereof, it is disposable after used. It does not need to explicitly close mapper instance, although the scope of the entire request to keep mapper instances there will not be any problems, but you will soon discover, like SqlSession as managing too many resources on the scope of the words It will be difficult to control. To avoid this complexity, it is preferable in the method mapper scope. The following example will demonstrate this practice:

try (SqlSession session = sqlSessionFactory.openSession()) {
  BlogMapper mapper = session.getMapper(BlogMapper.class);
  // 你的应用逻辑代码
}

Cenkaoziliao:
If you feel good you can also look at my other article in Spring bean life cycle
JavaEE Internet lightweight integrated development framework - Yang Kai array, Zhouji Wen, Liang Huahui, Tanmao Hua with
Mybatis official reference document

Published 28 original articles · won praise 155 · views 20000 +

Guess you like

Origin blog.csdn.net/weixin_42762133/article/details/97380239