Mybatis源码:SqlSessionFactory初始化

框架分层架构

本文基于Mybatis3.4.1

image-20210114092729612

SqlSessionFactory初始化

测试方法:

    private SqlSessionFactory getSqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        return new SqlSessionFactoryBuilder().build(inputStream);
    }

点击build方法,最后进入三个入参的build

这里主要创建一个xml的配置解析器,然后parser.parse(),断点进入该方法

image-20210114093436107

这里方法的parser是一个XPathParser类

image-20210114093913722

这里的XPathParser,通过该类,可以很方便的解析出xml(至于怎么解析xml,不在本文讨论之内)

进入parseConfiguration方法:这里就开始具体地解析

image-20210114094659901

以settingsElement为例,点击进入,这里有所有setting配置项,包括默认值,并且设置到configuration中

image-20210114095021662

跳出方法,进入mapperElement方法,我们去看mybatis是怎么解析mapper的

image-20210114100014201

点击进入mapperParser.parse()的方法

image-20210114100235180

点击进入configurationElement,看mybatis具体是怎么解析Sql映射文件

image-20210114100635405

进入buildStatementFromContext方法,看mybatis具体是如何解析增删改查标签的

image-20210114101221108

点击进入parseStatementNode(),

image-20210114101458133

进入addMappedStatement方法,最后会返回一个statement,它是MappedStatement对象

image-20210114101859814

statement对象的具体属性如下:包含sql语句,它的id等

image-20210114102140793

所以一个statement就代表一个增删改查的详细信息。

所以configuration中包含了所有配置文件的详细信息,包括sql映射文件和mybatis全局配置文件。

image-20210114102605853

configuration的部分重要属性:

image-20210114103259360

SqlSessionFactory创建结束:最后parse返回的configuration作为成员变量设置进DefualtSessionFactory,SqlSessionFactory创建结束。

image-20210114103420489

原文地址:https://www.cnblogs.com/wwjj4811/p/14276059.html