mybatis-spring start-up process and procedure calls

What mybatis-spring can do for us

mybatis framework has been very good, it is the general process of configuring and executing sql abstracts. Mybatis as long as you meet the requirements of the framework, first of all we have the correct configuration, and then there are model, interface layer, sql statement, and let the bean definition interface and sql associate, then when you execute a method in the interface, the framework will mybatis find the executable corresponding sql statement for you, then execute and return the results.

But this is not enough, the biggest problem is that many bean definition, must be hand-written one by one, and to ensure that the name and location of the interface and sql to be filled out correctly. The greatest contribution lies in its mybatis-spring bean scanning mechanism, as long as the notes used properly, it can automatically scan all interface and sql statement for you, and let them establish associate bean definitions. Spring can also create dynamic cache Bean definition, which is very cool.

In addition, since integrated into the Spring framework, mybatis configuration information and information SqlSessionFactory and the like, can also be used to manage the Spring Bean. Spring can do some caching them on its level.

mybatis perform a complete process of sql

We look back at a single mechanism mybatis, the complete process of loading and executing the configuration of sql.

// parse the configuration file, generating a configuration 
String Resource = "MyBatis-the config.xml" ; 
the InputStream inputStream = Resources.getResourceAsStream (Resource); 

// According to the configuration, a build a SqlSessionFactory 
a SqlSessionFactory SqlSessionFactory = new new the SqlSessionFactoryBuilder () Build (inputStream).;   

// get truly usable the SqlSession 
the SqlSession SQLSESSION = sqlSessionFactory.openSession (); 

// Get the agent from the interface of the SqlSession 
ArticleMapper articleMapperProxy = sqlSession.getMapper (ArticleMapper. class ); 

// perform the method in the proxy class 
Article article = articleMapperProxy. selectByPrimaryKey ( "123" ); 

// The following operations will be omitted for the article

 

mybatis-spring boot process

Let's say the startup process mybatis-spring frame. mybatis-spring and decided to take over sqlSessionFactory sqlSession, and create a proxy class sqlSessionProxy is sqlSession. In addition, mybatis-spring scannable interface mapper all layers, then the mapper over all proxy class. 2 line's break it down.

Line 1: sqlSessionFactory initialization and sqlSession

  1. Creating sqlSessionFactoryBean, it is to be a Spring-managed bean plant
  2. Creating sqlSessionFactory, which is managed by a Spring Bean, belongs to the category mybatis
  3. Creating sqlSessionTemplate, where to sqlSessionFactory, belong to the category mybatis-spring
  4. Creating sqlSessionProxy

SqlSessionFactory is a very important factory class, let's review what information SqlSessionFactory are:

Important information # sqlSessionFactory in 

SqlSessionFactory 
    the Configuration 
        Environment # there dataSource information 
        mapperRegistry 
            config # inside the configuration information 
            knownMappers # there are all the mapper 
        mappedStatements # there are all mapper of all methods 
        resultMaps # There are all xml all resultMap 
        sqlFragments # Inside All segments have sql

This information is important, and create sqlSessionProxy mapperProxy created in the future when the need to use inside information in the near future.

In mybatis-spring frame, sqlSessionFactory managed by Spring, let's look at how to create sqlSessionFactory out.

 1 @Bean(name = "sqlSessionFactory")
 2 public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
 3     SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
 4     factory.setDataSource(dataSource);
 5     if (StringUtils.hasText(this.properties.getConfig())) {
 6         factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfig()));
 7     } else {
 8         if (this.interceptors != null && this.interceptors.length > 0) {
 9             factory.setPlugins(this.interceptors);
10         }
11         factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
12         factory.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
13         factory.setMapperLocations(this.properties.getMapperLocations());
14     }
15     return factory.getObject();
16 }

Note: SqlSessionFactoryBean is a plant bean, which role is to parse the configuration mybatis (source data, alias, etc.), and then returns a SqlSessionFactory instance by getObject method. We look at what work SqlSessionFactoryBean is made during initialization.

Let us look at SqlSessionFactoryBean source:

 1 public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {
 2     private static final Log LOGGER = LogFactory.getLog(SqlSessionFactoryBean.class);
 3     private Resource configLocation;
 4     private Configuration configuration;
 5     private Resource[] mapperLocations;
 6     private DataSource dataSource;
 7     private TransactionFactory transactionFactory;
 8     private Properties configurationProperties;
 9     private SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
10     private SqlSessionFactory sqlSessionFactory;
11     private String environment = SqlSessionFactoryBean.class.getSimpleName();
12     private boolean failFast;
13     private Interceptor[] plugins;
14     private TypeHandler<?>[] typeHandlers;
15     private String typeHandlersPackage;
16     private Class<?>[] typeAliases;
17     private String typeAliasesPackage;
18     private Class<?> typeAliasesSuperType;
19     private DatabaseIdProvider databaseIdProvider;
20     private Class<? extends VFS> vfs;
21     private Cache cache;
22     private ObjectFactory objectFactory;
23     private ObjectWrapperFactory objectWrapperFactory;
24 
25     public SqlSessionFactoryBean() {
26     }
27     ...
28 }

We can see that this class implements FactoryBean, InitializingBean and ApplicationListener interface, the corresponding interface when bean initialization has implemented a number of specific methods, not to undertake here. Now look at what is important is the implementation of the method, these methods and what had been done.

// FactoryBean中的方法
public SqlSessionFactory getObject() throws Exception {
    if (this.sqlSessionFactory == null) {
        this.afterPropertiesSet();
    }

    return this.sqlSessionFactory;
}

By observing the code, getObject method returns the final sqlSessionFactory, if constructed sqlSessionFactory sqlSessionFactory empty afterPropertiesSet executes the buildSqlSessionFactory, mybatis to parse the configuration file will build sqlSessionFactory, build configuation. Behind onApplicationEvent mainly for something to do when the monitor application events (not to proceed, interested students can go to understand the next).

We take a look afterPropertiesSet method is how the property is set to go:

// InitializingBean中的方法
public void afterPropertiesSet() throws Exception {
    Assert.notNull(this.dataSource, "Property 'dataSource' is required");
    Assert.notNull(this.sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
    Assert.state(this.configuration == null && this.configLocation == null || this.configuration == null || this.configLocation == null, "Property 'the Configuration' and 'configLocation' CAN not specified with Together" ); 
    
    // see the familiar build method 
    the this .sqlSessionFactory = the this .buildSqlSessionFactory (); 
}

The main method buildSqlSessionFactory is: this.sqlSessionFactoryBuilder.build (configuration); not to undertake here. Up to this point, sqlSessionFactory has been created, let's take a brief look at the process of creating sqlSessionTemplate:

@Bean
@ConditionalOnMissingBean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
    return new SqlSessionTemplate(sqlSessionFactory, this.properties.getExecutorType());
}

If the track into, you will find new SqlSessionTemplate the same time, it creates sqlSessionProxy, not expand here.

 

Create a mapper scan and proxy class: line 2

interface must first be scanned, and then one by one to generate proxy classes, wait for the call. Let us look at this process:

  1. Use MapperScannerConfigurer
  2. scan () scan mapper
  3. setBeanClass
  4. Get MapperFactoryBean
  5. MapperFactoryBean.getObject () method
  6. configuration.getMapper
  7. getMapper
  8. Folders Registry
  9. knownMappers
  10. Ultimately resulting in a set MapperProxy, they are original mapper proxy. MapperProxy realized InvocationHandler interfaces, which invoke method, executed when the actual call.

Note: For point 4, MapperFactoryBean a bean plant, in the spring container, the plant is a special purpose bean, bean plant when the spring is injected into the other when the bean, bean plant itself it is not injected, it calls the bean getObject method.

 

mybatis-spring calling process

sqlSessionFactory after the initialization is complete, Mapper scanning and proxy class post is created, with these two prerequisites, we can call the procedure since the final stroke of a stroke of the mybatis-spring.

  1. Business code, you need to query the database, a method of mapper then call

  2. MapperProxy invoke
    • 2.1 if judgment
    • 2.2 else if judgment
    • 2.3 cachedMapperMethod focus method
    • 2.4 mapperMethod.execute focus method, the actual method of execution
  3. Depending on the type of sql statement, processing Points
    • case INSERT
    • case UPDATE
    • case DELETE
    • case SELECT
    • case FLUSH
  4. SELECT example to the situation, will perform sqlSession.selectList. At this time taken out is mapper of a proxy class

  5. sqlSessionTemplate.sqlSessionProxy.selectList

  6. SqlSessionInterceptor invoke
    • 6.1 getSqlSession, uses SqlSessionFactory , using sqlSessionHolder technology, took a not create a new one. In any case, there will be a sqlSession
    • 6.2 defaultSqlSession.selectList focus, followed by a query -> queryFromDatabase -> doQuery -> 1. prepareStatement 2. execute
    • 6.3 closeSqlSession

We can be found in mybatis-spring frame, real sqlSession creation, when the method is invoked only be carried out in the interface. Process can refer to more detailed above.

 

Reference material

  • https://segmentfault.com/a/1190000015165470

 

Created: 06/08/2019 21:00

 

Guess you like

Origin www.cnblogs.com/gkmeteor/p/11791509.html