Mybatis source parsing of flow analysis: initialization phase

GitHub address

Source resolve the address
https://github.com/erlieStar/mybatis-3

debug source code with project
https://github.com/erlieStar/mybatis-examples

Introduction

Mybatis core processes are divided into two stages

  1. Initialization phase: read XML configuration files and configuration information in the notes, create a configuration object, and the completion of initialization of each module
  2. Dynamic Agent stage: when the SQL execution, dynamic proxy class, parameter mapping is completed, the SQL execution, the mapping results

Mybatis the code initialization phase is still very clear, substantially is to various attributes in the configuration file is parsed, then the stored value to Configuration object. Profiles divided into two parts, 1.mybatis profile, 2.mapper mapping file.

Because parsing the configuration file is quite complex, so it mybatis with the builder mode, the process of creating objects and objects were decoupled. FIG pattern builder as UML

Here Insert Picture Description
Mainly has the following four roles:

  1. Behavior of various parts of the object: Builder (Builder) Interface
  2. DETAILED builder (ConcreteBuilder): There are generally two types of methods, one method of construction, such as buildPart1 (), 2 Construction method for obtaining a good product objects, such as The getProduct () method.
  3. Director (Director): by calling a specific builder, create needed products
  4. Users need to use complex objects: Product (Product)

XMLConfigBuilder: main-config.xml responsible for parsing the mybatis
XMLMapperBuilder: primarily responsible for resolving the map cache-ref configuration file, cache, parameterMap, resultMap, sql node
XMLStatementBuilder: mainly responsible for parsing the mapping configuration file select, insert, update, delete it four types of nodes

The sample project as follows

public class Part4Main {

    public static void main(String[] args) throws IOException {

        String resource = "mybatis-config4.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        // 这一句执行完后,Mybatis环境就初始化完了
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = null;
        try {
            sqlSession = sqlSessionFactory.openSession(true);
            AuthorMapper authorMapper = sqlSession.getMapper(AuthorMapper.class);
            List<Author> authorList = authorMapper.selectAuthortList();
            authorList.forEach(item -> {
                System.out.println(item);
            });
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }
}

When you start to look at the source code from one line to see, to see the final return SqlSessionFactory

SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

Various parsing rules I will not described in detail, against their own configuration files Debug few times will know. A timing chart of the resolution process is as follows
Here Insert Picture Description

Chase found last SqlSessionFactory returned to DefaultSqlSessionFactory

  public SqlSessionFactory build(Configuration config) {
    return new DefaultSqlSessionFactory(config);
  }

You can see the last parsed by generating a Configuration object, used to store various properties, and set to DefaultSqlSessionFactory, the Configuration object to look at what in the end kept things

  public DefaultSqlSessionFactory(Configuration configuration) {
    this.configuration = configuration;
  }

Some may be arranged in a boolean <setting> node, map directly to attributes Configuration object can look to the official website of the role of each attribute

protected boolean safeRowBoundsEnabled;
protected boolean safeResultHandlerEnabled = true;
protected boolean mapUnderscoreToCamelCase;
protected boolean aggressiveLazyLoading;

He said some of the more important attributes mappedStatements

protected final MapperRegistry mapperRegistry = new MapperRegistry(this);

Here Insert Picture Description
Initialized has generated a dynamic proxy class factory for each interface, this class will be used in the follow-up time of dynamic proxies

protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection");

Mapping of SQL node configuration file is parsed into MappedStatement objects, which SQL statements are parsed into objects SqlSource

Here Insert Picture Description

I can see a SQL put 2 times, key names, and interface methods are fully qualified name + method to put a name to.

Some simple SQL initialization time, it has been resolved to StaticSqlSource (may contain? The sql text), so that when executed as long as the corresponding parameters will be able to replace what execution

<delete id="deleteById" parameterType="int">
    delete from book where id = #{id}
</delete>

Here Insert Picture Description
I use this example to run behind the proxy process, do not select a node in order to allow you to quickly understand the entire process, and select the node mapping code is quite complex

While some other complex SQL is not, follow me add

Reference blog

[1]https://www.jianshu.com/p/7bc6d3b7fb45

Welcome attention

Here Insert Picture Description

Published 385 original articles · won praise 1471 · Views 900,000 +

Guess you like

Origin blog.csdn.net/zzti_erlie/article/details/104416601