打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
源码分析(1.4万字) | Mybatis接口没有实现类为什么可以执行增删改查

新的一年,所求皆如愿,所行化坦途

微信公众号:bugstack虫洞栈


沉淀、分享、成长,专注于原创专题案例,以最易学习编程的方式分享知识,让自己和他人都能有所收获。目前已完成的专题有;Netty4.x实战专题案例、用Java实现JVM、基于JavaAgent的全链路监控、手写RPC框架、架构设计专题案例[Ing]等。

你用剑🗡、我用刀🔪,好的代码都很烧😏,望你不吝出招💨!

  • 目录

  • 一、前言介绍

  • 二、案例工程

  • 三、环境配置

  • 四、(mybatis)源码分析

    • 1. 从一个简单的案例开始

    • 2. 容器初始化

    • 3. 配置文件解析

    • 4. Mapper加载与动态代理

  • 五、(mybatis-spring)源码分析

    • 1. 从一个简单的案例开始

    • 2. 扫描装配注册(MapperScannerConfigurer)

    • 3. SqlSession容器工厂初始化(SqlSessionFactoryBean)

  • 六、综上总结

一、前言介绍

MyBatis 是一款非常优秀的持久层框架,相对于IBatis更是精进了不少。与此同时它还提供了很多的扩展点,比如最常用的插件;语言驱动器,执行器,对象工厂,对象包装器工厂等等都可以扩展。那么,如果想成为一个有深度的男人(程序猿),还是应该好好的学习一下这款开源框架的源码,以此可以更好的领会设计模式的精髓(面试?)。其实可能平常的业务开发中,并不会去深究各个框架的源代码,也常常会听到即使不会也可以开发代码。但!每个人的目标不同,就像;代码写的好工资加的少(没有bug怎么看出你工作嘞!),好!为了改变世界,开始分析喽!

在分析之前先出一个题,看看你适合看源码不;

1@Test
2public void test(){
3    B b = new B();
4    b.scan();  //我的输出结果是什么?
5}
6static class A {
7    public void scan(){
8        doScan();
9    }
10    protected void doScan(){
11        System.out.println("A.doScan");
12    }
13}
14static class B extends A {
15    @Override
16    protected void doScan() {
17        System.out.println("B.doScan");
18    }
19}

其实无论你的答案对错,都不影响你对源码的分析。只不过,往往在一些框架中会有很多的设计模式和开发技巧,如果上面的代码在你平时的开发中几乎没用过,那么可能你暂时更多的还是开发着CRUD的功能(莫慌,我还写过PHP呢)。

接下来先分析Mybatis单独使用时的源码执行过程,再分析Mybatis+Spring整合源码,好!开始。

二、案例工程

为了更好的分析,我们创建一个Mybaits的案例工程,其中包括;Mybatis单独使用、Mybatis+Spring整合使用

1itstack-demo-mybatis
2└── src
3    ├── main
4    │   ├── java
5    │   │   └── org.itstack.demo
6    │   │       ├── dao
7    │   │       │    ├── ISchool.java        
8    │   │       │    └── IUserDao.java   
9    │   │       └── interfaces     
10    │   │             ├── School.java 
11    │   │            └── User.java
12    │   ├── resources    
13    │   │   ├── mapper
14    │   │   │   ├── School_Mapper.xml
15    │   │   │   └── User_Mapper.xml
16    │   │   ├── props    
17    │   │   │   └── jdbc.properties
18    │   │   ├── spring
19    │   │   │   ├── mybatis-config-datasource.xml
20    │   │   │   └── spring-config-datasource.xml
21    │   │   ├── logback.xml
22    │   │   ├── mybatis-config.xml
23    │   │   └── spring-config.xml
24    │   └── webapp
25    │       └── WEB-INF
26    └── test
27         └── java
28             └── org.itstack.demo.test
29                 ├── MybatisApiTest.java
30                 └── SpringApiTest.java

三、环境配置

  1. JDK1.8

  2. IDEA 2019.3.1

  3. mybatis 3.4.6 {不同版本源码略有差异和bug修复}

  4. mybatis-spring 1.3.2 {以下源码分析会说代码行号,注意不同版本可能会有差异}

四、(mybatis)源码分析

1<dependency>
2    <groupId>org.mybatis</groupId>
3    <artifactId>mybatis</artifactId>
4    <version>3.4.6</version>
5</dependency>

Mybatis的整个源码还是很大的,以下主要将部分核心内容进行整理分析,以便于后续分析Mybatis与Spring整合的源码部分。简要包括;容器初始化、配置文件解析、Mapper加载与动态代理。

1. 从一个简单的案例开始

要学习Mybatis源码,最好的方式一定是从一个简单的点进入,而不是从Spring整合开始分析。SqlSessionFactory是整个Mybatis的核心实例对象,SqlSessionFactory对象的实例又通过SqlSessionFactoryBuilder对象来获得。SqlSessionFactoryBuilder对象可以从XML配置文件加载配置信息,然后创建SqlSessionFactory。如下例子:

MybatisApiTest.java

1public class MybatisApiTest {
2
3    @Test
4    public void test_queryUserInfoById() {
5        String resource = "spring/mybatis-config-datasource.xml";
6        Reader reader;
7        try {
8            reader = Resources.getResourceAsReader(resource);
9            SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
10
11            SqlSession session = sqlMapper.openSession();
12            try {
13                User user = session.selectOne("org.itstack.demo.dao.IUserDao.queryUserInfoById"1L);
14                System.out.println(JSON.toJSONString(user));
15            } finally {
16                session.close();
17                reader.close();
18            }
19        } catch (IOException e) {
20            e.printStackTrace();
21        }
22    }
23
24}

dao/IUserDao.java

1public interface IUserDao {
2
3     User queryUserInfoById(Long id);
4
5}

spring/mybatis-config-datasource.xml

1<?xml version="1.0" encoding="UTF-8"?>
2<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
3        "http://mybatis.org/dtd/mybatis-3-config.dtd">
4
5<configuration>
6    <environments default="development">
7        <environment id="development">
8            <transactionManager type="JDBC"/>
9            <dataSource type="POOLED">
10                <property name="driver" value="com.mysql.jdbc.Driver"/>
11                <property name="url" value="jdbc:mysql://127.0.0.1:3306/itstack?useUnicode=true"/>
12                <property name="username" value="root"/>
13                <property name="password" value="123456"/>
14            </dataSource>
15        </environment>
16    </environments>
17
18    <mappers>
19        <mapper resource="mapper/User_Mapper.xml"/>
20    </mappers>
21
22</configuration>

如果一切顺利,那么会有如下结果:

1{"age":18,"createTime":1571376957000,"id":1,"name":"花花","updateTime":1571376957000}

从上面的代码块可以看到,核心代码;SqlSessionFactoryBuilder().build(reader),负责Mybatis配置文件的加载、解析、构建等职责,直到最终可以通过SqlSession来执行并返回结果。

2. 容器初始化

从上面代码可以看到,SqlSessionFactory是通过SqlSessionFactoryBuilder工厂类创建的,而不是直接使用构造器。容器的配置文件加载和初始化流程如下:

微信公众号:bugstack虫洞栈 & 初始化流程
  • 流程核心类

  • SqlSessionFactoryBuilder

  • XMLConfigBuilder

  • XPathParser

  • Configuration

SqlSessionFactoryBuilder.java

1public class SqlSessionFactoryBuilder {
2
3  public SqlSessionFactory build(Reader reader) {
4    return build(reader, nullnull);
5  }
6
7  public SqlSessionFactory build(Reader reader, String environment) {
8    return build(reader, environment, null);
9  }
10
11  public SqlSessionFactory build(Reader reader, Properties properties) {
12    return build(reader, null, properties);
13  }
14
15  public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
16    try {
17      XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
18      return build(parser.parse());
19    } catch (Exception e) {
20      throw ExceptionFactory.wrapException("Error building SqlSession.", e);
21    } finally {
22      ErrorContext.instance().reset();
23      try {
24        reader.close();
25      } catch (IOException e) {
26        // Intentionally ignore. Prefer previous error.
27      }
28    }
29  }
30
31  public SqlSessionFactory build(InputStream inputStream) {
32    return build(inputStream, nullnull);
33  }
34
35  public SqlSessionFactory build(InputStream inputStream, String environment) {
36    return build(inputStream, environment, null);
37  }
38
39  public SqlSessionFactory build(InputStream inputStream, Properties properties) {
40    return build(inputStream, null, properties);
41  }
42
43  public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
44    try {
45      XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
46      return build(parser.parse());
47    } catch (Exception e) {
48      throw ExceptionFactory.wrapException("Error building SqlSession.", e);
49    } finally {
50      ErrorContext.instance().reset();
51      try {
52        inputStream.close();
53      } catch (IOException e) {
54        // Intentionally ignore. Prefer previous error.
55      }
56    }
57  }
58
59  public SqlSessionFactory build(Configuration config) {
60    return new DefaultSqlSessionFactory(config);
61  }
62
63}

从上面的源码可以看到,SqlSessionFactory提供三种方式build构建对象;

  • 字节流:java.io.InputStream

  • 字符流:java.io.Reader

  • 配置类:org.apache.ibatis.session.Configuration

那么,字节流、字符流都会创建配置文件解析类:XMLConfigBuilder,并通过parser.parse()生成Configuration,最后调用配置类构建方法生成SqlSessionFactory。

XMLConfigBuilder.java

1public class XMLConfigBuilder extends BaseBuilder {
2
3  private boolean parsed;
4  private final XPathParser parser;
5  private String environment;
6  private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory();
7
8  ...
9  public XMLConfigBuilder(Reader reader, String environment, Properties props) {
10    this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);
11  }
12  ...
13}  
  1. XMLConfigBuilder对于XML文件的加载和解析都委托于XPathParser,最终使用JDK自带的javax.xml进行XML解析(XPath)

  2. XPathParser(Reader reader, boolean validation, Properties variables, EntityResolver entityResolver)

  3. reader:使用字符流创建新的输入源,用于对XML文件的读取

  4. validation:是否进行DTD校验

  5. variables:属性配置信息

  6. entityResolver:Mybatis硬编码了new XMLMapperEntityResolver()提供XML默认解析器

XMLMapperEntityResolver.java

1public class XMLMapperEntityResolver implements EntityResolver {
2
3  private static final String IBATIS_CONFIG_SYSTEM = "ibatis-3-config.dtd";
4  private static final String IBATIS_MAPPER_SYSTEM = "ibatis-3-mapper.dtd";
5  private static final String MYBATIS_CONFIG_SYSTEM = "mybatis-3-config.dtd";
6  private static final String MYBATIS_MAPPER_SYSTEM = "mybatis-3-mapper.dtd";
7
8  private static final String MYBATIS_CONFIG_DTD = "org/apache/ibatis/builder/xml/mybatis-3-config.dtd";
9  private static final String MYBATIS_MAPPER_DTD = "org/apache/ibatis/builder/xml/mybatis-3-mapper.dtd";
10
11  /*
12   * Converts a public DTD into a local one
13   * 
14   * @param publicId The public id that is what comes after "PUBLIC"
15   * @param systemId The system id that is what comes after the public id.
16   * @return The InputSource for the DTD
17   * 
18   * @throws org.xml.sax.SAXException If anything goes wrong
19   */

20  @Override
21  public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
22    try {
23      if (systemId != null) {
24        String lowerCaseSystemId = systemId.toLowerCase(Locale.ENGLISH);
25        if (lowerCaseSystemId.contains(MYBATIS_CONFIG_SYSTEM) || lowerCaseSystemId.contains(IBATIS_CONFIG_SYSTEM)) {
26          return getInputSource(MYBATIS_CONFIG_DTD, publicId, systemId);
27        } else if (lowerCaseSystemId.contains(MYBATIS_MAPPER_SYSTEM) || lowerCaseSystemId.contains(IBATIS_MAPPER_SYSTEM)) {
28          return getInputSource(MYBATIS_MAPPER_DTD, publicId, systemId);
29        }
30      }
31      return null;
32    } catch (Exception e) {
33      throw new SAXException(e.toString());
34    }
35  }
36
37  private InputSource getInputSource(String path, String publicId, String systemId) {
38    InputSource source = null;
39    if (path != null) {
40      try {
41        InputStream in = Resources.getResourceAsStream(path);
42        source = new InputSource(in);
43        source.setPublicId(publicId);
44        source.setSystemId(systemId);        
45      } catch (IOException e) {
46        // ignore, null is ok
47      }
48    }
49    return source;
50  }
51
52}
  1. Mybatis依赖于dtd文件进行进行解析,其中的ibatis-3-config.dtd主要是用于兼容用途

  2. getInputSource(String path, String publicId, String systemId)的调用里面有两个参数publicId(公共标识符)和systemId(系统标示符)

XPathParser.java

1public XPathParser(Reader reader, boolean validation, Properties variables, EntityResolver entityResolver) {
2  commonConstructor(validation, variables, entityResolver);
3  this.document = createDocument(new InputSource(reader));
4}
5
6private void commonConstructor(boolean validation, Properties variables, EntityResolver entityResolver) {
7  this.validation = validation;
8  this.entityResolver = entityResolver;
9  this.variables = variables;
10  XPathFactory factory = XPathFactory.newInstance();
11  this.xpath = factory.newXPath();
12}
13
14private Document createDocument(InputSource inputSource) {
15  // important: this must only be called AFTER common constructor
16  try {
17    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
18    factory.setValidating(validation);
19    factory.setNamespaceAware(false);
20    factory.setIgnoringComments(true);
21    factory.setIgnoringElementContentWhitespace(false);
22    factory.setCoalescing(false);
23    factory.setExpandEntityReferences(true);
24    DocumentBuilder builder = factory.newDocumentBuilder();
25    builder.setEntityResolver(entityResolver);
26    builder.setErrorHandler(new ErrorHandler() {
27      @Override
28      public void error(SAXParseException exception) throws SAXException {
29        throw exception;
30      }
31      @Override
32      public void fatalError(SAXParseException exception) throws SAXException {
33        throw exception;
34      }
35      @Override
36      public void warning(SAXParseException exception) throws SAXException {
37      }
38    });
39    return builder.parse(inputSource);
40  } catch (Exception e) {
41    throw new BuilderException("Error creating document instance.  Cause: " + e, e);
42  }
43
44}    
  1. 从上到下可以看到主要是为了创建一个Mybatis的文档解析器,最后根据builder.parse(inputSource)返回Document

  2. 得到XPathParser实例后,接下来在调用方法:this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);

    1XMLConfigBuilder.this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);
    2
    3private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {
    4  super(new Configuration());
    5  ErrorContext.instance().resource("SQL Mapper Configuration");
    6  this.configuration.setVariables(props);
    7  this.parsed = false;
    8  this.environment = environment;
    9  this.parser = parser;
    10}
  3. 其中调用了父类的构造函数

    1public abstract class BaseBuilder {
    2 protected final Configuration configuration;
    3 protected final TypeAliasRegistry typeAliasRegistry;
    4 protected final TypeHandlerRegistry typeHandlerRegistry;
    5
    6 public BaseBuilder(Configuration configuration) {
    7   this.configuration = configuration;
    8   this.typeAliasRegistry = this.configuration.getTypeAliasRegistry();
    9   this.typeHandlerRegistry = this.configuration.getTypeHandlerRegistry();
    10 }
    11}
  4. XMLConfigBuilder创建完成后,sqlSessionFactoryBuild调用parser.parse()创建Configuration

    1public class XMLConfigBuilder extends BaseBuilder {    
    2    public Configuration parse() {
    3      if (parsed) {
    4        throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    5      }
    6      parsed = true;
    7      parseConfiguration(parser.evalNode("/configuration"));
    8      return configuration;
    9    }
    10}

3. 配置文件解析

这一部分是整个XML文件解析和装载的核心内容,其中包括;

  1. 属性解析propertiesElement

  2. 加载settings节点settingsAsProperties

  3. 载自定义VFS loadCustomVfs

  4. 解析类型别名typeAliasesElement

  5. 加载插件pluginElement

  6. 加载对象工厂objectFactoryElement

  7. 创建对象包装器工厂objectWrapperFactoryElement

  8. 加载反射工厂reflectorFactoryElement

  9. 元素设置settingsElement

  10. 加载环境配置environmentsElement

  11. 数据库厂商标识加载databaseIdProviderElement

  12. 加载类型处理器typeHandlerElement

  13. (核心)加载mapper文件mapperElement

1parseConfiguration(parser.evalNode("/configuration"));
2
3private void parseConfiguration(XNode root) {
4    try {
5      //issue #117 read properties first
6      //属性解析propertiesElement
7      propertiesElement(root.evalNode("properties"));
8      //加载settings节点settingsAsProperties
9      Properties settings = settingsAsProperties(root.evalNode("settings"));
10      //加载自定义VFS loadCustomVfs
11      loadCustomVfs(settings);
12      //解析类型别名typeAliasesElement
13      typeAliasesElement(root.evalNode("typeAliases"));
14      //加载插件pluginElement
15      pluginElement(root.evalNode("plugins"));
16      //加载对象工厂objectFactoryElement
17      objectFactoryElement(root.evalNode("objectFactory"));
18      //创建对象包装器工厂objectWrapperFactoryElement
19      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
20      //加载反射工厂reflectorFactoryElement
21      reflectorFactoryElement(root.evalNode("reflectorFactory"));
22      //元素设置
23      settingsElement(settings);
24      // read it after objectFactory and objectWrapperFactory issue #631
25      //加载环境配置environmentsElement
26      environmentsElement(root.evalNode("environments"));
27      //数据库厂商标识加载databaseIdProviderElement
28      databaseIdProviderElement(root.evalNode("databaseIdProvider"));
29      //加载类型处理器typeHandlerElement
30      typeHandlerElement(root.evalNode("typeHandlers"));
31      //加载mapper文件mapperElement
32      mapperElement(root.evalNode("mappers"));
33    } catch (Exception e) {
34      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
35    }
36

所有的root.evalNode()底层都是调用XML DOM方法:Object evaluate(String expression, Object item, QName returnType),表达式参数expression,通过XObject resultObject = eval( expression, item )返回最终节点内容,可以参考http://mybatis.org/dtd/mybatis-3-config.dtd,如下;

1<!ELEMENT configuration (properties?, settings?, typeAliases?, typeHandlers?, objectFactory?, objectWrapperFactory?, reflectorFactory?, plugins?, environments?, databaseIdProvider?, mappers?)>
2
3<!ELEMENT databaseIdProvider (property*)>
4<!ATTLIST databaseIdProvider
5type CDATA #REQUIRED
6>

7
8<!ELEMENT properties (property*)>
9<!ATTLIST properties
10resource CDATA #IMPLIED
11url CDATA #IMPLIED
12>

13
14<!ELEMENT property EMPTY>
15<!ATTLIST property
16name CDATA #REQUIRED
17value CDATA #REQUIRED
18>

19
20<!ELEMENT settings (setting+)>
21
22<!ELEMENT setting EMPTY>
23<!ATTLIST setting
24name CDATA #REQUIRED
25value CDATA #REQUIRED
26>

27
28<!ELEMENT typeAliases (typeAlias*,package*)>
29
30<!ELEMENT typeAlias EMPTY>
31<!ATTLIST typeAlias
32type CDATA #REQUIRED
33alias CDATA #IMPLIED
34>

35
36<!ELEMENT typeHandlers (typeHandler*,package*)>
37
38<!ELEMENT typeHandler EMPTY>
39<!ATTLIST typeHandler
40javaType CDATA #IMPLIED
41jdbcType CDATA #IMPLIED
42handler CDATA #REQUIRED
43>

44
45<!ELEMENT objectFactory (property*)>
46<!ATTLIST objectFactory
47type CDATA #REQUIRED
48>

49
50<!ELEMENT objectWrapperFactory EMPTY>
51<!ATTLIST objectWrapperFactory
52type CDATA #REQUIRED
53>

54
55<!ELEMENT reflectorFactory EMPTY>
56<!ATTLIST reflectorFactory
57type CDATA #REQUIRED
58>

59
60<!ELEMENT plugins (plugin+)>
61
62<!ELEMENT plugin (property*)>
63<!ATTLIST plugin
64interceptor CDATA #REQUIRED
65>

66
67<!ELEMENT environments (environment+)>
68<!ATTLIST environments
69default CDATA #REQUIRED
70>

71
72<!ELEMENT environment (transactionManager,dataSource)>
73<!ATTLIST environment
74id CDATA #REQUIRED
75>

76
77<!ELEMENT transactionManager (property*)>
78<!ATTLIST transactionManager
79type CDATA #REQUIRED
80>

81
82<!ELEMENT dataSource (property*)>
83<!ATTLIST dataSource
84type CDATA #REQUIRED
85>

86
87<!ELEMENT mappers (mapper*,package*)>
88
89<!ELEMENT mapper EMPTY>
90<!ATTLIST mapper
91resource CDATA #IMPLIED
92url CDATA #IMPLIED
93class CDATA #IMPLIED
94>

95
96<!ELEMENT package EMPTY>
97<!ATTLIST package
98name CDATA #REQUIRED
99>

mybatis-3-config.dtd 定义文件中有11个配置文件,如下;

  1. properties?,

  2. settings?,

  3. typeAliases?,

  4. typeHandlers?,

  5. objectFactory?,

  6. objectWrapperFactory?,

  7. reflectorFactory?,

  8. plugins?,

  9. environments?,

  10. databaseIdProvider?,

  11. mappers?

以上每个配置都是可选。最终配置内容会保存到org.apache.ibatis.session.Configuration,如下;

1public class Configuration {
2
3  protected Environment environment;
4  // 允许在嵌套语句中使用分页(RowBounds)。如果允许使用则设置为false。默认为false
5  protected boolean safeRowBoundsEnabled;
6  // 允许在嵌套语句中使用分页(ResultHandler)。如果允许使用则设置为false。
7  protected boolean safeResultHandlerEnabled = true;
8  // 是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。默认false
9  protected boolean mapUnderscoreToCamelCase;
10  // 当开启时,任何方法的调用都会加载该对象的所有属性。否则,每个属性会按需加载。默认值false (true in ≤3.4.1)
11  protected boolean aggressiveLazyLoading;
12  // 是否允许单一语句返回多结果集(需要兼容驱动)。
13  protected boolean multipleResultSetsEnabled = true;
14  // 允许 JDBC 支持自动生成主键,需要驱动兼容。这就是insert时获取mysql自增主键/oracle sequence的开关。注:一般来说,这是希望的结果,应该默认值为true比较合适。
15  protected boolean useGeneratedKeys;
16  // 使用列标签代替列名,一般来说,这是希望的结果
17  protected boolean useColumnLabel = true;
18  // 是否启用缓存 {默认是开启的,可能这也是你的面试题}
19  protected boolean cacheEnabled = true;
20  // 指定当结果集中值为 null 的时候是否调用映射对象的 setter(map 对象时为 put)方法,这对于有 Map.keySet() 依赖或 null 值初始化的时候是有用的。
21  protected boolean callSettersOnNulls;
22  // 允许使用方法签名中的名称作为语句参数名称。 为了使用该特性,你的工程必须采用Java 8编译,并且加上-parameters选项。(从3.4.1开始)
23  protected boolean useActualParamName = true;
24  //当返回行的所有列都是空时,MyBatis默认返回null。 当开启这个设置时,MyBatis会返回一个空实例。 请注意,它也适用于嵌套的结果集 (i.e. collectioin and association)。(从3.4.2开始) 注:这里应该拆分为两个参数比较合适, 一个用于结果集,一个用于单记录。通常来说,我们会希望结果集不是null,单记录仍然是null
25  protected boolean returnInstanceForEmptyRow;
26  // 指定 MyBatis 增加到日志名称的前缀。
27  protected String logPrefix;
28  // 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。一般建议指定为slf4j或log4j
29  protected Class <? extends Log> logImpl;
30   // 指定VFS的实现, VFS是mybatis提供的用于访问AS内资源的一个简便接口
31  protected Class <? extends VFS> vfsImpl;
32  // MyBatis 利用本地缓存机制(Local Cache)防止循环引用(circular references)和加速重复嵌套查询。 默认值为 SESSION,这种情况下会缓存一个会话中执行的所有查询。 若设置值为 STATEMENT,本地会话仅用在语句执行上,对相同 SqlSession 的不同调用将不会共享数据。
33  protected LocalCacheScope localCacheScope = LocalCacheScope.SESSION;
34  // 当没有为参数提供特定的 JDBC 类型时,为空值指定 JDBC 类型。 某些驱动需要指定列的 JDBC 类型,多数情况直接用一般类型即可,比如 NULL、VARCHAR 或 OTHER。
35  protected JdbcType jdbcTypeForNull = JdbcType.OTHER;
36  // 指定对象的哪个方法触发一次延迟加载。
37  protected Set<String> lazyLoadTriggerMethods = new HashSet<String>(Arrays.asList(new String[] { "equals""clone""hashCode""toString" }));
38  // 设置超时时间,它决定驱动等待数据库响应的秒数。默认不超时
39  protected Integer defaultStatementTimeout;
40  // 为驱动的结果集设置默认获取数量。
41  protected Integer defaultFetchSize;
42  // SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(prepared statements);BATCH 执行器将重用语句并执行批量更新。
43  protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
44  // 指定 MyBatis 应如何自动映射列到字段或属性。NONE 表示取消自动映射;PARTIAL 只会自动映射没有定义嵌套结果集映射的结果集。FULL 会自动映射任意复杂的结果集(无论是否嵌套)。
45  protected AutoMappingBehavior autoMappingBehavior = AutoMappingBehavior.PARTIAL;
46  // 指定发现自动映射目标未知列(或者未知属性类型)的行为。这个值应该设置为WARNING比较合适
47  protected AutoMappingUnknownColumnBehavior autoMappingUnknownColumnBehavior = AutoMappingUnknownColumnBehavior.NONE;
48  // settings下的properties属性
49  protected Properties variables = new Properties();
50  // 默认的反射器工厂,用于操作属性、构造器方便
51  protected ReflectorFactory reflectorFactory = new DefaultReflectorFactory();
52  // 对象工厂, 所有的类resultMap类都需要依赖于对象工厂来实例化
53  protected ObjectFactory objectFactory = new DefaultObjectFactory();
54  // 对象包装器工厂,主要用来在创建非原生对象,比如增加了某些监控或者特殊属性的代理类
55  protected ObjectWrapperFactory objectWrapperFactory = new DefaultObjectWrapperFactory();
56  // 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。特定关联关系中可通过设置fetchType属性来覆盖该项的开关状态。
57  protected boolean lazyLoadingEnabled = false;
58  // 指定 Mybatis 创建具有延迟加载能力的对象所用到的代理工具。MyBatis 3.3+使用JAVASSIST
59  protected ProxyFactory proxyFactory = new JavassistProxyFactory(); // #224 Using internal Javassist instead of OGNL
60  // MyBatis 可以根据不同的数据库厂商执行不同的语句,这种多厂商的支持是基于映射语句中的 databaseId 属性。
61  protected String databaseId;
62  ...
63}

以上可以看到,Mybatis把所有的配置;resultMap、Sql语句、插件、缓存等都维护在Configuration中。这里还有一个小技巧,在Configuration还有一个StrictMap内部类,它继承于HashMap完善了put时防重、get时取不到值的异常处理,如下;

1protected static class StrictMap<Vextends HashMap<StringV{
2
3    private static final long serialVersionUID = -4950446264854982944L;
4    private final String name;
5
6    public StrictMap(String name, int initialCapacity, float loadFactor) {
7      super(initialCapacity, loadFactor);
8      this.name = name;
9    }
10
11    public StrictMap(String name, int initialCapacity) {
12      super(initialCapacity);
13      this.name = name;
14    }
15
16    public StrictMap(String name) {
17      super();
18      this.name = name;
19    }
20
21    public StrictMap(String name, Map<String, ? extends V> m) {
22      super(m);
23      this.name = name;
24    }
25}    

(核心)加载mapper文件mapperElement

Mapper文件处理是Mybatis框架的核心服务,所有的SQL语句都编写在Mapper中,这块也是我们分析的重点,其他模块可以后续讲解。

XMLConfigBuilder.parseConfiguration()->mapperElement(root.evalNode("mappers"));

1private void mapperElement(XNode parent) throws Exception {
2   if (parent != null) {
3     for (XNode child : parent.getChildren()) {
4       // 如果要同时使用package自动扫描和通过mapper明确指定要加载的mapper,一定要确保package自动扫描的范围不包含明确指定的mapper,否则在通过package扫描的interface的时候,尝试加载对应xml文件的loadXmlResource()的逻辑中出现判重出错,报org.apache.ibatis.binding.BindingException异常,即使xml文件中包含的内容和mapper接口中包含的语句不重复也会出错,包括加载mapper接口时自动加载的xml mapper也一样会出错。
5       if ("package".equals(child.getName())) {
6         String mapperPackage = child.getStringAttribute("name");
7         configuration.addMappers(mapperPackage);
8       } else {
9         String resource = child.getStringAttribute("resource");
10         String url = child.getStringAttribute("url");
11         String mapperClass = child.getStringAttribute("class");
12         if (resource != null && url == null && mapperClass == null) {
13           ErrorContext.instance().resource(resource);
14           InputStream inputStream = Resources.getResourceAsStream(resource);
15           XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
16           mapperParser.parse();
17         } else if (resource == null && url != null && mapperClass == null) {
18           ErrorContext.instance().resource(url);
19           InputStream inputStream = Resources.getUrlAsStream(url);
20           XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
21           mapperParser.parse();
22         } else if (resource == null && url == null && mapperClass != null) {
23           Class<?> mapperInterface = Resources.classForName(mapperClass);
24           configuration.addMapper(mapperInterface);
25         } else {
26           throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
27         }
28       }
29     }
30   }
31}
  • Mybatis提供了两类配置Mapper的方法,第一类是使用package自动搜索的模式,这样指定package下所有接口都会被注册为mapper,也是在Spring中比较常用的方式,例如:

    1<mappers>
    2<package name="org.itstack.demo"/>
    3</mappers>
  • 另外一类是明确指定Mapper,这又可以通过resource、url或者class进行细分,例如;

    1<mappers>
    2  <mapper resource="mapper/User_Mapper.xml"/>
    3  <mapper class=""/>
    4  <mapper url=""/>
    5</mappers>

4. Mapper加载与动态代理

通过package方式自动搜索加载,生成对应的mapper代理类,代码块和流程,如下;

1private void mapperElement(XNode parent) throws Exception {
2  if (parent != null) {
3    for (XNode child : parent.getChildren()) {
4      if ("package".equals(child.getName())) {
5        String mapperPackage = child.getStringAttribute("name");
6        configuration.addMappers(mapperPackage);
7      } else {
8        ...
9      }
10    }
11  }
12}
微信公众号:bugstack虫洞栈 & 动态代理过程

Mapper加载到生成代理对象的流程中,主要的核心类包括;

  1. XMLConfigBuilder

  2. Configuration

  3. MapperRegistry

  4. MapperAnnotationBuilder

  5. MapperProxyFactory

MapperRegistry.java

解析加载Mapper

1public void addMappers(String packageName, Class<?> superType) {
2  // mybatis框架提供的搜索classpath下指定package以及子package中符合条件(注解或者继承于某个类/接口)的类,默认使用Thread.currentThread().getContextClassLoader()返回的加载器,和spring的工具类殊途同归。
3  ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<Class<?>>();   
4  // 无条件的加载所有的类,因为调用方传递了Object.class作为父类,这也给以后的指定mapper接口预留了余地
5  resolverUtil.find(new ResolverUtil.IsA(superType), packageName); 
6 // 所有匹配的calss都被存储在ResolverUtil.matches字段中
7  Set<Class<? extends Class<?>>> mapperSet = resolverUtil.getClasses();
8  for (Class<?> mapperClass : mapperSet) {   
9    //调用addMapper方法进行具体的mapper类/接口解析
10    addMapper(mapperClass);
11  }
12}

生成代理类:MapperProxyFactory

1public <T> void addMapper(Class<T> type) {    
2  // 对于mybatis mapper接口文件,必须是interface,不能是class
3  if (type.isInterface()) {
4    if (hasMapper(type)) {
5      throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
6    }
7    boolean loadCompleted = false;
8    try {      
9      // 为mapper接口创建一个MapperProxyFactory代理
10      knownMappers.put(type, new MapperProxyFactory<T>(type));
11      // It's important that the type is added before the parser is run
12      // otherwise the binding may automatically be attempted by the
13      // mapper parser. If the type is already known, it won't try.
14      MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
15      parser.parse();
16      loadCompleted = true;
17    } finally {
18      if (!loadCompleted) {
19        knownMappers.remove(type);
20      }
21    }
22  }
23}

在MapperRegistry中维护了接口类与代理工程的映射关系,knownMappers;

1private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();

MapperProxyFactory.java

1public class MapperProxyFactory<T{
2  private final Class<T> mapperInterface;
3  private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();
4  public MapperProxyFactory(Class<T> mapperInterface) {
5    this.mapperInterface = mapperInterface;
6  }
7  public Class<T> getMapperInterface() {
8    return mapperInterface;
9  }
10  public Map<Method, MapperMethod> getMethodCache() {
11    return methodCache;
12  }
13  @SuppressWarnings("unchecked")
14  protected T newInstance(MapperProxy<T> mapperProxy) {
15    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
16  }
17  public T newInstance(SqlSession sqlSession) {
18    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
19    return newInstance(mapperProxy);
20  }
21}

如上是Mapper的代理类工程,构造函数中的mapperInterface就是对应的接口类,当实例化时候会获得具体的MapperProxy代理,里面主要包含了SqlSession。

五、(mybatis-spring)源码分析

1<dependency>
2    <groupId>org.mybatis</groupId>
3    <artifactId>mybatis-spring</artifactId>
4    <version>1.3.2</version>
5</dependency>

作为一款好用的ORM框架,一定是萝莉脸(单纯)、御姐心(强大),铺的了床(屏蔽与JDBC直接打交道)、暖的了房(速度性能好)!鉴于这些优点几乎在国内互联网大部分开发框架都会使用到Mybatis,尤其在一些需要高性能的场景下需要优化sql那么一定需要手写sql在xml中。那么,准备好了吗!开始分析分析它的源码;

1. 从一个简单的案例开始

与分析mybatis源码一样,先做一个简单的案例;定义dao、编写配置文件、junit单元测试;

SpringApiTest.java

1@RunWith(SpringJUnit4ClassRunner.class)
2@ContextConfiguration("classpath:spring-config.xml")
3public class SpringApiTest {
4
5    private Logger logger = LoggerFactory.getLogger(SpringApiTest.class);
6
7    @Resource
8    private ISchoolDao schoolDao;
9    @Resource
10    private IUserDao userDao;
11
12    @Test
13    public void test_queryRuleTreeByTreeId(){
14        School ruleTree = schoolDao.querySchoolInfoById(1L);
15        logger.info(JSON.toJSONString(ruleTree));
16
17        User user = userDao.queryUserInfoById(1L);
18        logger.info(JSON.toJSONString(user));
19    }
20
21}
1 

spring-config-datasource.xml

1<?xml version="1.0" encoding="UTF-8"?>
2<beans xmlns="http://www.springframework.org/schema/beans"
3       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4       xsi:schemaLocation="http://www.springframework.org/schema/beans
5        http://www.springframework.org/schema/beans/spring-beans.xsd"
>

6
7    <!-- 1.数据库连接池:DriverManagerDataSource 也可以使用DBCP2-->
8    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
9        <property name="driverClassName" value="${db.jdbc.driverClassName}"/>
10        <property name="url" value="${db.jdbc.url}"/>
11        <property name="username" value="${db.jdbc.username}"/>
12        <property name="password" value="${db.jdbc.password}"/>
13    </bean>
14
15    <!-- 2.配置SqlSessionFactory对象 -->
16    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
17        <!-- 注入数据库连接池 -->
18        <property name="dataSource" ref="dataSource"/>
19        <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
20        <property name="configLocation" value="classpath:mybatis-config.xml"/>
21        <!-- 扫描entity包 使用别名 -->
22        <property name="typeAliasesPackage" value="org.itstack.demo.po"/>
23        <!-- 扫描sql配置文件:mapper需要的xml文件 -->
24        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
25    </bean>
26
27    <!-- 3.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
28    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
29        <!-- 注入sqlSessionFactory -->
30        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
31        <!-- 给出需要扫描Dao接口包,多个逗号隔开 -->
32        <property name="basePackage" value="org.itstack.demo.dao"/>
33    </bean>
34
35</beans>

如果一切顺利,那么会有如下结果:

1{"address":"北京市海淀区颐和园路5号","createTime":1571376957000,"id":1,"name":"北京大学","updateTime":1571376957000}
2{"age":18,"createTime":1571376957000,"id":1,"name":"花花","updateTime":1571376957000}

从上面单元测试的代码可以看到,两个没有方法体的注解就这么神奇的执行了我们的xml中的配置语句并输出了结果。其实主要得益于以下两个类;

  • org.mybatis.spring.SqlSessionFactoryBean

  • org.mybatis.spring.mapper.MapperScannerConfigurer

2. 扫描装配注册(MapperScannerConfigurer)

MapperScannerConfigurer为整个Dao接口层生成动态代理类注册,启动到了核心作用。这个类实现了如下接口,用来对扫描的Mapper进行处理:

  • BeanDefinitionRegistryPostProcessor

  • InitializingBean

  • ApplicationContextAware

  • BeanNameAware

整体类图如下;

微信公众号:bugstack虫洞栈 & MapperScannerConfigurer类图

执行流程如下;

微信公众号:bugstack虫洞栈 & 执行流程图

上面的类图+流程图,其实已经很清楚的描述了MapperScannerConfigurer初始化过程,但对于头一次看的新人来说依旧是我太难了,好继续!

MapperScannerConfigurer.java & 部分截取

1@Override
2public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
3  if (this.processPropertyPlaceHolders) {
4    processPropertyPlaceHolders();
5  }
6  ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
7  scanner.setAddToConfig(this.addToConfig);
8  scanner.setAnnotationClass(this.annotationClass);
9  scanner.setMarkerInterface(this.markerInterface);
10  scanner.setSqlSessionFactory(this.sqlSessionFactory);
11  scanner.setSqlSessionTemplate(this.sqlSessionTemplate);
12  scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);
13  scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName);
14  scanner.setResourceLoader(this.applicationContext);
15  scanner.setBeanNameGenerator(this.nameGenerator);
16  scanner.registerFilters();
17  scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
18}
  • 实现了BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry用于注册Bean到Spring容器中

  • 306行:new ClassPathMapperScanner(registry); 硬编码类路径扫描器,用于解析Mybatis的Mapper文件

  • 317行:scanner.scan 对Mapper进行扫描。这里包含了一个继承类实现关系的调用,也就是本文开头的测试题。

ClassPathMapperScanner.java & 部分截取

1@Override
2public Set<BeanDefinitionHolder> doScan(String... basePackages) {
3  Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);
4  if (beanDefinitions.isEmpty()) {
5    logger.warn("No MyBatis mapper was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration.");
6  } else {
7    processBeanDefinitions(beanDefinitions);
8  }
9  return beanDefinitions;
10}
  • 优先调用父类的super.doScan(basePackages);进行注册Bean信息

ClassPathBeanDefinitionScanner.java & 部分截取

1protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
2    Assert.notEmpty(basePackages, "At least one base package must be specified");
3    Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>();
4    for (String basePackage : basePackages) {
5        Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
6        for (BeanDefinition candidate : candidates) {
7            ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
8            candidate.setScope(scopeMetadata.getScopeName());
9            String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
10            if (candidate instanceof AbstractBeanDefinition) {
11                postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
12            }
13            if (candidate instanceof AnnotatedBeanDefinition) {
14                AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate)
15            }
16            if (checkCandidate(beanName, candidate)) {
17                BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
18                definitionHolder =
19                        AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.regi
20                beanDefinitions.add(definitionHolder);
21                registerBeanDefinition(definitionHolder, this.registry);
22            }
23        }
24    }
25    return beanDefinitions;
26}
  • 优先调用了父类的doScan方法,用于Mapper扫描和Bean的定义以及注册到DefaultListableBeanFactory。{DefaultListableBeanFactory是Spring中IOC容器的始祖,所有需要实例化的类都需要注册进来,之后在初始化}

  • 272行:findCandidateComponents(basePackage),扫描package包路径,对于注解类的有另外的方式,大同小异

  • 288行:registerBeanDefinition(definitionHolder, this.registry);注册Bean信息的过程,最终会调用到:org.springframework.beans.factory.support.DefaultListableBeanFactory

ClassPathMapperScanner.java & 部分截取

1**processBeanDefinitions(beanDefinitions);**
2
3private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
4  GenericBeanDefinition definition;
5  for (BeanDefinitionHolder holder : beanDefinitions) {
6    definition = (GenericBeanDefinition) holder.getBeanDefinition();
7    if (logger.isDebugEnabled()) {
8      logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName() 
9        + "' and '" + definition.getBeanClassName() + "' mapperInterface");
10    }
11    // the mapper interface is the original class of the bean
12    // but, the actual class of the bean is MapperFactoryBean
13    definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); // issue #59
14    definition.setBeanClass(this.mapperFactoryBean.getClass());
15    definition.getPropertyValues().add("addToConfig"this.addToConfig);
16    boolean explicitFactoryUsed = false;
17    if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {
18      definition.getPropertyValues().add("sqlSessionFactory"new RuntimeBeanReference(this.sqlSessionFactoryBeanName));
19      explicitFactoryUsed = true;
20    } else if (this.sqlSessionFactory != null) {
21      definition.getPropertyValues().add("sqlSessionFactory"this.sqlSessionFactory);
22      explicitFactoryUsed = true;
23    }
24    if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) {
25      if (explicitFactoryUsed) {
26        logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
27      }
28      definition.getPropertyValues().add("sqlSessionTemplate"new RuntimeBeanReference(this.sqlSessionTemplateBeanName));
29      explicitFactoryUsed = true;
30    } else if (this.sqlSessionTemplate != null) {
31      if (explicitFactoryUsed) {
32        logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
33      }
34      definition.getPropertyValues().add("sqlSessionTemplate"this.sqlSessionTemplate);
35      explicitFactoryUsed = true;
36    }
37    if (!explicitFactoryUsed) {
38      if (logger.isDebugEnabled()) {
39        logger.debug("Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'.");
40      }
41      definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
42    }
43  }
44}
  • 163行:super.doScan(basePackages);,调用完父类方法后开始执行内部方法:processBeanDefinitions(beanDefinitions)

  • 186行:definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); 设置BeanName参数,也就是我们的:ISchoolDao、IUserDao

  • 187行:definition.setBeanClass(this.mapperFactoryBean.getClass());,设置BeanClass,接口本身是没有类的,那么这里将MapperFactoryBean类设置进来,最终所有的dao层接口类都是这个MapperFactoryBean

MapperFactoryBean.java & 部分截取

这个类有继承也有接口实现,最好先了解下整体类图,如下;

微信公众号:bugstack虫洞栈 & MapperFactoryBean类图

这个类就非常重要了,最终所有的sql信息执行都会通过这个类获取getObject(),也就是SqlSession获取mapper的代理类:MapperProxyFactory->MapperProxy

1public class MapperFactoryBean<Textends SqlSessionDaoSupport implements FactoryBean<T{
2
3  private Class<T> mapperInterface;
4
5  private boolean addToConfig = true;
6
7  public MapperFactoryBean() {
8    //intentionally empty 
9  }
10
11  public MapperFactoryBean(Class<T> mapperInterface) {
12    this.mapperInterface = mapperInterface;
13  }
14
15  /**  
16   * 当SpringBean容器初始化时候会调用到checkDaoConfig(),他是继承类中的抽象方法
17   * {@inheritDoc}
18   */

19  @Override
20  protected void checkDaoConfig() {
21    super.checkDaoConfig();
22
23    notNull(this.mapperInterface, "Property 'mapperInterface' is required");
24
25    Configuration configuration = getSqlSession().getConfiguration();
26    if (this.addToConfig && !configuration.hasMapper(this.mapperInterface)) {
27      try {
28        configuration.addMapper(this.mapperInterface);
29      } catch (Exception e) {
30        logger.error("Error while adding the mapper '" + this.mapperInterface + "' to configuration.", e);
31        throw new IllegalArgumentException(e);
32      } finally {
33        ErrorContext.instance().reset();
34      }
35    }
36  }
37
38  /**
39   * {@inheritDoc}
40   */

41  @Override
42  public T getObject() throws Exception {
43    return getSqlSession().getMapper(this.mapperInterface);
44  }
45
46  ...
47}
  • 72行:checkDaoConfig(),当SpringBean容器初始化时候会调用到checkDaoConfig(),他是继承类中的抽象方法

  • 95行:getSqlSession().getMapper(this.mapperInterface);,通过接口获取Mapper(代理类),调用过程如下;

    1public <T> getMapper(Class<T> type, SqlSession sqlSession) {
    2  final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
    3  if (mapperProxyFactory == null) {
    4    throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
    5  }
    6  try {
    7    return mapperProxyFactory.newInstance(sqlSession);
    8  } catch (Exception e) {
    9    throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    10  }
    11}
    1@SuppressWarnings("unchecked")
    2protected T newInstance(MapperProxy<T> mapperProxy) {
    3  return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
    4}
    5public T newInstance(SqlSession sqlSession) {
    6  final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    7  return newInstance(mapperProxy);
    8}
    • mapperProxyFactory.newInstance(sqlSession);,通过反射工程生成MapperProxy

    • DefaultSqlSession.getMapper(Class

       type),获取Mapper
    • Configuration.getMapper(Class

       type, SqlSession sqlSession),从配置中获取
    • MapperRegistry.getMapper(Class

       type, SqlSession sqlSession),从注册中心获取到实例化生成

MapperProxy.java & 部分截取

1public class MapperProxy<Timplements InvocationHandlerSerializable {
2
3  private static final long serialVersionUID = -6424540398559729838L;
4  private final SqlSession sqlSession;
5  private final Class<T> mapperInterface;
6  private final Map<Method, MapperMethod> methodCache;
7
8  public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
9    this.sqlSession = sqlSession;
10    this.mapperInterface = mapperInterface;
11    this.methodCache = methodCache;
12  }
13
14  @Override
15  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
16    try {
17      if (Object.class.equals(method.getDeclaringClass())) {
18        return method.invoke(this, args);
19      } else if (isDefaultMethod(method)) {
20        return invokeDefaultMethod(proxy, method, args);
21      }
22    } catch (Throwable t) {
23      throw ExceptionUtil.unwrapThrowable(t);
24    }
25    final MapperMethod mapperMethod = cachedMapperMethod(method);
26    return mapperMethod.execute(sqlSession, args);
27  }
28
29  private MapperMethod cachedMapperMethod(Method method) {
30    MapperMethod mapperMethod = methodCache.get(method);
31    if (mapperMethod == null) {
32      mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
33      methodCache.put(method, mapperMethod);
34    }
35    return mapperMethod;
36  }
37
38  @UsesJava7
39  private Object invokeDefaultMethod(Object proxy, Method method, Object[] args)
40      throws Throwable 
{
41    final Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class
42        .getDeclaredConstructor(Class.class, int.class);
43    if (!constructor.isAccessible()) {
44      constructor.setAccessible(true);
45    }
46    final Class<?> declaringClass = method.getDeclaringClass();
47    return constructor
48        .newInstance(declaringClass,
49            MethodHandles.Lookup.PRIVATE | MethodHandles.Lookup.PROTECTED
50                | MethodHandles.Lookup.PACKAGE | MethodHandles.Lookup.PUBLIC)
51        .unreflectSpecial(method, declaringClass).bindTo(proxy).invokeWithArguments(args);
52  }
53
54  ...
55}
  • 58行:final MapperMethod mapperMethod = cachedMapperMethod(method);,从缓存中获取MapperMethod

  • 59行:mapperMethod.execute(sqlSession, args);,执行SQL语句,并返回结果(到这关于查询获取结果就到骨头(干)层了);INSERT、UPDATE、DELETE、SELECT

    1public Object execute(SqlSession sqlSession, Object[] args) {
    2Object result;
    3switch (command.getType()) {
    4  case INSERT: {
    5  Object param = method.convertArgsToSqlCommandParam(args);
    6    result = rowCountResult(sqlSession.insert(command.getName(), param));
    7    break;
    8  }
    9  case UPDATE: {
    10    Object param = method.convertArgsToSqlCommandParam(args);
    11    result = rowCountResult(sqlSession.update(command.getName(), param));
    12    break;
    13  }
    14  case DELETE: {
    15    Object param = method.convertArgsToSqlCommandParam(args);
    16    result = rowCountResult(sqlSession.delete(command.getName(), param));
    17    break;
    18  }
    19  case SELECT:
    20    if (method.returnsVoid() && method.hasResultHandler()) {
    21      executeWithResultHandler(sqlSession, args);
    22      result = null;
    23    } else if (method.returnsMany()) {
    24      result = executeForMany(sqlSession, args);
    25    } else if (method.returnsMap()) {
    26      result = executeForMap(sqlSession, args);
    27    } else if (method.returnsCursor()) {
    28      result = executeForCursor(sqlSession, args);
    29    } else {
    30      Object param = method.convertArgsToSqlCommandParam(args);
    31      result = sqlSession.selectOne(command.getName(), param);
    32    }
    33    break;
    34  case FLUSH:
    35    result = sqlSession.flushStatements();
    36    break;
    37  default:
    38    throw new BindingException("Unknown execution method for: " + command.getName());
    39}
    40if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
    41  throw new BindingException("Mapper method '" + command.getName() 
    42      + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
    43}
    44return result;
    45}

以上对于MapperScannerConfigurer这一层就分析完了,从扫描定义注入到为Spring容器准备Bean的信息,代理、反射、SQL执行,基本就包括全部核心内容了,接下来在分析下SqlSessionFactoryBean

3. SqlSession容器工厂初始化(SqlSessionFactoryBean)

SqlSessionFactoryBean初始化过程中需要对一些自身内容进行处理,因此也需要实现如下接口;

  • FactoryBean

  • InitializingBean -> void afterPropertiesSet() throws Exception

  • ApplicationListener

微信公众号:bugstack虫洞栈 & SqlSessionFactoryBean初始化流程

以上的流程其实已经很清晰的描述整个核心流程,但同样对于新手上路会有障碍,那么!好,继续!

SqlSessionFactoryBean.java & 部分截取

1public void afterPropertiesSet() throws Exception {
2  notNull(dataSource, "Property 'dataSource' is required");
3  notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
4  state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null),
5            "Property 'configuration' and 'configLocation' can not specified with together");
6  this.sqlSessionFactory = buildSqlSessionFactory();
7}
  • afterPropertiesSet(),InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候都会执行该方法。

  • 380行:buildSqlSessionFactory();内部方法构建,核心功能继续往下看。

SqlSessionFactoryBean.java & 部分截取

1protected SqlSessionFactory buildSqlSessionFactory() throws IOException {
2  Configuration configuration;
3  XMLConfigBuilder xmlConfigBuilder = null;
4
5  ...
6
7  if (!isEmpty(this.mapperLocations)) {
8    for (Resource mapperLocation : this.mapperLocations) {
9      if (mapperLocation == null) {
10        continue;
11      }
12      try {
13        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
14            configuration, mapperLocation.toString(), configuration.getSqlFragments());
15        xmlMapperBuilder.parse();
16      } catch (Exception e) {
17        throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
18      } finally {
19        ErrorContext.instance().reset();
20      }
21      if (LOGGER.isDebugEnabled()) {
22        LOGGER.debug("Parsed mapper file: '" + mapperLocation + "'");
23      }
24    }
25  } else {
26    if (LOGGER.isDebugEnabled()) {
27      LOGGER.debug("Property 'mapperLocations' was not specified or no matching resources found");
28    }
29  }
30  return this.sqlSessionFactoryBuilder.build(configuration);
31}
  • 513行:for (Resource mapperLocation : this.mapperLocations) 循环解析Mapper内容

  • 519行:XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(…) 解析XMLMapperBuilder

  • 521行:xmlMapperBuilder.parse() 执行解析,具体如下;

XMLMapperBuilder.java & 部分截取

1public class XMLMapperBuilder extends BaseBuilder {
2   private final XPathParser parser;
3   private final MapperBuilderAssistant builderAssistant;
4   private final Map<String, XNode> sqlFragments;
5   private final String resource;
6
7   private void bindMapperForNamespace() {
8     String namespace = builderAssistant.getCurrentNamespace();
9     if (namespace != null) {
10       Class<?> boundType = null;
11       try {
12         boundType = Resources.classForName(namespace);
13       } catch (ClassNotFoundException e) {
14         //ignore, bound type is not required
15       }
16       if (boundType != null) {
17         if (!configuration.hasMapper(boundType)) {
18           // Spring may not know the real resource name so we set a flag
19           // to prevent loading again this resource from the mapper interface
20           // look at MapperAnnotationBuilder#loadXmlResource
21           configuration.addLoadedResource("namespace:" + namespace);
22           configuration.addMapper(boundType);
23         }
24       }
25     }
26   }
27}
  • 这里413行非常重要,configuration.addMapper(boundType);,真正到了添加Mapper到配置中心

MapperRegistry.java & 部分截取

1public class MapperRegistry {
2
3  public <T> void addMapper(Class<T> type) {
4    if (type.isInterface()) {
5      if (hasMapper(type)) {
6        throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
7      }
8      boolean loadCompleted = false;
9      try {
10        knownMappers.put(type, new MapperProxyFactory<T>(type));
11        // It's important that the type is added before the parser is run
12        // otherwise the binding may automatically be attempted by the
13        // mapper parser. If the type is already known, it won't try.
14        MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
15        parser.parse();
16        loadCompleted = true;
17      } finally {
18        if (!loadCompleted) {
19          knownMappers.remove(type);
20        }
21      }
22    }
23  }
24
25}
  • 67行:创建代理工程knownMappers.put(type, new MapperProxyFactory

    (type));

截至到这,MapperScannerConfigurer、SqlSessionFactoryBean,两个类干的事情就相融合了;

  • 第一个用于扫描Dao接口设置代理类注册到IOC中,用于后续生成Bean实体类,MapperFactoryBean,并可以通过mapperInterface从Configuration获取Mapper

  • 另一个用于生成SqlSession工厂初始化,解析Mapper里的XML配置进行动态代理MapperProxyFactory->MapperProxy注入到Configuration的Mapper

  • 最终在注解类的帮助下进行方法注入,等执行操作时候即可获得动态代理对象,从而执行相应的CRUD操作

    1@Resource
    2private ISchoolDao schoolDao;
    3
    4schoolDao.querySchoolInfoById(1L);

六、综上总结

  • 分析过程较长篇幅也很大,不一定一天就能看懂整个流程,但当耐下心来一点点研究,还是可以获得很多的收获的。以后在遇到这类的异常就可以迎刃而解了,同时也有助于面试、招聘!

  • 之所以分析Mybatis最开始是想在Dao上加自定义注解,发现切面拦截不到。想到这是被动态代理的类,之后层层往往下扒直到MapperProxy.invoke!当然,Mybatis提供了自定义插件开发。

  • 以上的源码分析只是对部分核心内容进行分析,如果希望了解全部可以参考资料;MyBatis 3源码深度解析,并调试代码。IDEA中还是很方便看源码的,包括可以查看类图、调用顺序等。

  • mybatis、mybatis-spring中其实最重要的是将Mapper配置文件解析与接口类组装成代理类进行映射,以此来方便对数据库的CRUD操作。从源码分析后,可以获得更多的编程经验(套路)。

  • Mybatis相关链接;

    • https://github.com/mybatis/mybatis-3

    • https://mybatis.org/mybatis-3/zh/index.html

    • https://github.com/fuzhengwei/itstack-demo-code-mybatis


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Mybatis源码详解
Mybatis中配置Mapper的方法
源码分析Mybatis MapperProxy初始化【图文并茂】
MyBatis 学习笔记
Mybatis mapper动态代理的原理详解
MyBatis入门基础(一)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服