1. 简单Demo

  1. String resource = "mybatis-config.xml";
  2. //1.流形式读取mybatis配置文件
  3. InputStream stream = Resources.getResourceAsStream(resource);
  4. //2.通过配置文件创建SqlSessionFactory
  5. SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(stream);
  6. //3.通过SqlSessionFactory创建sqlSession
  7. SqlSession session = sessionFactory.openSession();
  8. //4.通过SqlSession执行Sql语句获取结果
  9. List<User> userList = session.selectList("selectAll");
  10. System.out.println(userList.size());

1.通过InputStream获取mybatis的配置文件
2.通过SqlSessionFactoryBuilder创建SqlSessionFactory
3.通过SqlSessionFactory创建一个SqlSession
4.通过SqlSession执行Sql语句并获取结果
那么接下来先来了解下SqlSessionFactoryBuilder、SqlSessionFactory、SqlSession都是什么,是怎么工作的?

2. SqlSessionFactoryBuilder 分析

SqlSessionFactoryBuilder是SqlSessionFactory的构造类,而SqlSessionFactory又是SqlSession的工厂接口,SqlSession从字面意思可知是sql会话接口;
所以SqlSessionFactoryBuilder可定义为Sql会话工厂构造类,顾名思义此类的作用就是创建SqlSessionFactory

  1. package org.apache.ibatis.session;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.Reader;
  5. import java.util.Properties;
  6. import org.apache.ibatis.builder.xml.XMLConfigBuilder;
  7. import org.apache.ibatis.exceptions.ExceptionFactory;
  8. import org.apache.ibatis.executor.ErrorContext;
  9. import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;
  10. public class SqlSessionFactoryBuilder {
  11. //方法1
  12. public SqlSessionFactory build(Reader reader) {
  13. return build(reader, null, null);
  14. }
  15. //方法2
  16. public SqlSessionFactory build(Reader reader, String environment) {
  17. return build(reader, environment, null);
  18. }
  19. //方法3
  20. public SqlSessionFactory build(Reader reader, Properties properties) {
  21. return build(reader, null, properties);
  22. }
  23. //方法4
  24. public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
  25. try {
  26. XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
  27. return build(parser.parse());
  28. } catch (Exception e) {
  29. throw ExceptionFactory.wrapException("Error building SqlSession.", e);
  30. } finally {
  31. ErrorContext.instance().reset();
  32. try {
  33. reader.close();
  34. } catch (IOException e) {
  35. // Intentionally ignore. Prefer previous error.
  36. }
  37. }
  38. }
  39. //方法5
  40. public SqlSessionFactory build(InputStream inputStream) {
  41. return build(inputStream, null, null);
  42. }
  43. //方法6
  44. public SqlSessionFactory build(InputStream inputStream, String environment) {
  45. return build(inputStream, environment, null);
  46. }
  47. //方法7
  48. public SqlSessionFactory build(InputStream inputStream, Properties properties) {
  49. return build(inputStream, null, properties);
  50. }
  51. //方法8
  52. public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
  53. try {
  54. XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
  55. // 解析mybatis的xml配置文件,封装为Configuration对象
  56. return build(parser.parse());
  57. } catch (Exception e) {
  58. throw ExceptionFactory.wrapException("Error building SqlSession.", e);
  59. } finally {
  60. ErrorContext.instance().reset();
  61. try {
  62. inputStream.close();
  63. } catch (IOException e) {
  64. // Intentionally ignore. Prefer previous error.
  65. }
  66. }
  67. }
  68. //方法9
  69. public SqlSessionFactory build(Configuration config) {
  70. return new DefaultSqlSessionFactory(config);
  71. }

由源码可知该类共有9个public方法,方法1、2、3最终都是调用了方法4;而方法5、6、7最终都是调用了方法8;而方法4和方法8都是根据传参创建了一个XMLConfiguration对象。
然后根据XMLConfiguration对象的parse方法创建了一个Configuration对象,然后都调用了方法9,所以该类的所有方法最终都是调用了方法9。而方法9是根据传入的Configuration参数新建了一个DefaultSqlSessionFactory对象返回。
很显然DefaultSqlSessionFactory是SqlSessionFactory接口的默认实现类(SqlSessionFactory还有一个SqlSessionManager实现类,后续继续了解)
总结:SqlSessionFactoryBuilder根据mybatis的配置文件流创建Configuration对象,然后新建一个SqlSessionFactory的默认实现类DefaultSqlSessionFactory的对象

3. SqlSessionFactory 分析

  1. package org.apache.ibatis.session;
  2. import java.sql.Connection;
  3. /**
  4. * Creates an {@link SqlSession} out of a connection or a DataSource
  5. *
  6. * @author Clinton Begin
  7. */
  8. public interface SqlSessionFactory {
  9. SqlSession openSession();
  10. SqlSession openSession(boolean autoCommit);
  11. SqlSession openSession(Connection connection);
  12. SqlSession openSession(TransactionIsolationLevel level);
  13. SqlSession openSession(ExecutorType execType);
  14. SqlSession openSession(ExecutorType execType, boolean autoCommit);
  15. SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level);
  16. SqlSession openSession(ExecutorType execType, Connection connection);
  17. /**
  18. * 获取Configuration 对象,这个对象包含了MyBatis的配置信息,Mapper接口等信息的描述
  19. * @return MyBatis配置信息
  20. */
  21. Configuration getConfiguration();
  22. }

SqlSessionFactory接口定义了8个创建SqlSession的接口,和一个获取Configuration的方法,该接口的主要作用也就是创建SqlSession
可以看出这里面涉及到了几个参数:
autoCommit:数据库是否自动提交
Connection:数据库连接
TransactionIsolationLevel:数据库隔离级别
ExecutorType:执行器类型
这几个参数具体含义暂不讨论,后续继续了解,那么现在继续了解下SqlSessionFactory的默认实现类DefaultSqlSessionFactory

4. DefaultSqlSessionFactory 分析

  1. package org.apache.ibatis.session.defaults;
  2. import java.sql.Connection;
  3. import java.sql.SQLException;
  4. import org.apache.ibatis.exceptions.ExceptionFactory;
  5. import org.apache.ibatis.executor.ErrorContext;
  6. import org.apache.ibatis.executor.Executor;
  7. import org.apache.ibatis.mapping.Environment;
  8. import org.apache.ibatis.session.Configuration;
  9. import org.apache.ibatis.session.ExecutorType;
  10. import org.apache.ibatis.session.SqlSession;
  11. import org.apache.ibatis.session.SqlSessionFactory;
  12. import org.apache.ibatis.session.TransactionIsolationLevel;
  13. import org.apache.ibatis.transaction.Transaction;
  14. import org.apache.ibatis.transaction.TransactionFactory;
  15. import org.apache.ibatis.transaction.managed.ManagedTransactionFactory;
  16. /**
  17. * @author Clinton Begin
  18. */
  19. public class DefaultSqlSessionFactory implements SqlSessionFactory {
  20. private final Configuration configuration;
  21. public DefaultSqlSessionFactory(Configuration configuration) {
  22. this.configuration = configuration;
  23. }
  24. @Override
  25. public SqlSession openSession() {
  26. return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
  27. }
  28. @Override
  29. public SqlSession openSession(boolean autoCommit) {
  30. return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, autoCommit);
  31. }
  32. @Override
  33. public SqlSession openSession(ExecutorType execType) {
  34. return openSessionFromDataSource(execType, null, false);
  35. }
  36. @Override
  37. public SqlSession openSession(TransactionIsolationLevel level) {
  38. return openSessionFromDataSource(configuration.getDefaultExecutorType(), level, false);
  39. }
  40. @Override
  41. public SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level) {
  42. return openSessionFromDataSource(execType, level, false);
  43. }
  44. @Override
  45. public SqlSession openSession(ExecutorType execType, boolean autoCommit) {
  46. return openSessionFromDataSource(execType, null, autoCommit);
  47. }
  48. @Override
  49. public SqlSession openSession(Connection connection) {
  50. return openSessionFromConnection(configuration.getDefaultExecutorType(), connection);
  51. }
  52. @Override
  53. public SqlSession openSession(ExecutorType execType, Connection connection) {
  54. return openSessionFromConnection(execType, connection);
  55. }
  56. @Override
  57. public Configuration getConfiguration() {
  58. return configuration;
  59. }
  60. private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
  61. Transaction tx = null;
  62. try {
  63. final Environment environment = configuration.getEnvironment();
  64. final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
  65. tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
  66. final Executor executor = configuration.newExecutor(tx, execType);
  67. return new DefaultSqlSession(configuration, executor, autoCommit);
  68. } catch (Exception e) {
  69. closeTransaction(tx); // may have fetched a connection so lets call close()
  70. throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
  71. } finally {
  72. ErrorContext.instance().reset();
  73. }
  74. }
  75. private SqlSession openSessionFromConnection(ExecutorType execType, Connection connection) {
  76. try {
  77. boolean autoCommit;
  78. try {
  79. autoCommit = connection.getAutoCommit();
  80. } catch (SQLException e) {
  81. // Failover to true, as most poor drivers
  82. // or databases won't support transactions
  83. autoCommit = true;
  84. }
  85. final Environment environment = configuration.getEnvironment();
  86. final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
  87. final Transaction tx = transactionFactory.newTransaction(connection);
  88. final Executor executor = configuration.newExecutor(tx, execType);
  89. return new DefaultSqlSession(configuration, executor, autoCommit);
  90. } catch (Exception e) {
  91. throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
  92. } finally {
  93. ErrorContext.instance().reset();
  94. }
  95. }
  96. private TransactionFactory getTransactionFactoryFromEnvironment(Environment environment) {
  97. if (environment == null || environment.getTransactionFactory() == null) {
  98. return new ManagedTransactionFactory();
  99. }
  100. return environment.getTransactionFactory();
  101. }
  102. private void closeTransaction(Transaction tx) {
  103. if (tx != null) {
  104. try {
  105. tx.close();
  106. } catch (SQLException ignore) {
  107. // Intentionally ignore. Prefer previous error.
  108. }
  109. }
  110. }
  111. }

DefaultSqlSessionFactory除了实现了SqlSessionFactory的9个接口,还有一个构造方法,也就是SqlSessionFactoryBuilder中调用的那个,然后还有4个私有方法。
可以看出实现的8个创建SqlSession对象的接口最终都是调用了openSessionFromDataSource()或是openSessionFromConnection()两个方法,以openSessionFromDataSource()为例,源码如下:

4.1. openSessionFromDataSource()

  1. private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
  2. Transaction tx = null;
  3. try {
  4. //根据Configuration获取环境参数对象
  5. final Environment environment = configuration.getEnvironment();
  6. //根据环境参数对象获取事务工厂对象
  7. final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
  8. //根据事务工厂创建新的事务对象
  9. tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
  10. //根据Configuration获取执行器对象
  11. final Executor executor = configuration.newExecutor(tx, execType);
  12. //根据3个参数创建DefaultSqlSession对象
  13. return new DefaultSqlSession(configuration, executor, autoCommit);
  14. } catch (Exception e) {
  15. closeTransaction(tx); // may have fetched a connection so lets call close()
  16. throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
  17. } finally {
  18. ErrorContext.instance().reset();
  19. }
  20. }

openSessionFromDataSource() 共有三个参数

  1. ExecutorType:执行器类型
  2. TransactionIsolationLevel:事务隔离级别
  3. autoCommit:自动提交标识

通过源码分析,最终是创建了一个DefaultSqlSession对象,很明显是SqlSession接口的默认实现类;
openSessionFromConnection方法和openSessionFromDataSource的区别就是参数不同,效果是一样的,最终也是返回一个DefaultSqlSession对象
而具体的Sql的执行都是通过DefaultSqlSession对象去执行的。具体怎么执行的后续再了解。
总结:
1.先获取mybatis的配置文件,解析成流对象(字符流和字节流都可以)Reader和InputStream都可以
2.通过SqlSessionFactoryBuilder根据mybatis的配置文件流创建一个Configuration对象
3.SqlSessionFactoryBuilder根据Configuration对象创建一个DefaultSqlSessionFactory(SqlSessionFactory的默认实现类)
4.DefaulatSqlSessionFacotry根据传入的参数,创建一个DefaultSqlSession对象(SqlSession的默认实现类)

5. XMLConfigBuilder 分析

XMLConfigBuilder类的作用是对mybatis-config.xml配置文件的解析,在SqlSessionFactoryBuilder 类中解析MyBatis配置文件时创建,位于org.apache.ibatis.builder.xml目录下,继承于BaseBuilder类,关于BaseBuilder类后续再看。
XMLConfigBuilder看名字能猜到是关于mybatis的XML配置的构造类,负责构造mybatis的XML配置的。
XMLConfigBuilder共有四个属性,代码如下:

  1. //解析标识,因为Configuration是全局变量,只需要解析创建一次即可,true表示已经解析创建过,false则表示没有
  2. private boolean parsed;
  3. private final XPathParser parser;
  4. //环境参数
  5. private String environment;
  6. private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory();

XMLConfigBuilder共有6个public构造方法和一个private的构造方法

  1. public XMLConfigBuilder(Reader reader) {
  2. this(reader, null, null);
  3. }
  4. public XMLConfigBuilder(Reader reader, String environment) {
  5. this(reader, environment, null);
  6. }
  7. public XMLConfigBuilder(Reader reader, String environment, Properties props) {
  8. this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);
  9. }
  10. public XMLConfigBuilder(InputStream inputStream) {
  11. this(inputStream, null, null);
  12. }
  13. public XMLConfigBuilder(InputStream inputStream, String environment) {
  14. this(inputStream, environment, null);
  15. }
  16. public XMLConfigBuilder(InputStream inputStream, String environment, Properties props) {
  17. this(new XPathParser(inputStream, true, props, new XMLMapperEntityResolver()), environment, props);
  18. }
  19. private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {
  20. //调用父类的构造方法
  21. super(new Configuration());
  22. ErrorContext.instance().resource("SQL Mapper Configuration");
  23. this.configuration.setVariables(props);
  24. this.parsed = false;
  25. this.environment = environment;
  26. this.parser = parser;
  27. }

这6个public的构造方法都是根据mybatis的配置文件流创建一个XPathParser对象,然后最终都调用了私有的构造方法,而私有的构造方法先是调用了父类BaseBuilder的构造方法,然后分别根据参数给四个属性赋值。
在SqlSessionFactoryBuilder中解析MyBatis文件是通过创建一个XMLConfigBuilder对象,然后调用了对象的parse()方法获取到一个Configuration对象。接下来就先看看XMLConfigBuilder的parse()方法,如下:

  1. public Configuration parse() {
  2. //判断Configuration是否解析过,Configuration是全局变量,只需要解析创建一次即可
  3. if (parsed) {
  4. throw new BuilderException("Each XMLConfigBuilder can only be used once.");
  5. }
  6. parsed = true;
  7. //调用下面的方法,parser.evalNode("/configuration")解析XML配置的configuration节点的内容,得到XNode对象
  8. parseConfiguration(parser.evalNode("/configuration"));
  9. return configuration;
  10. }
  11. /**
  12. * 根据root中存储的是configuration节点的内容
  13. * @param root
  14. */
  15. private void parseConfiguration(XNode root) {
  16. try {
  17. // issue #117 read properties first
  18. //设置properties配置
  19. propertiesElement(root.evalNode("properties"));
  20. //设置settings配置
  21. Properties settings = settingsAsProperties(root.evalNode("settings"));
  22. loadCustomVfs(settings);
  23. loadCustomLogImpl(settings);
  24. //设置typeAliases配置
  25. typeAliasesElement(root.evalNode("typeAliases"));
  26. //设置plugins配置
  27. pluginElement(root.evalNode("plugins"));
  28. //设置objectFactory配置
  29. objectFactoryElement(root.evalNode("objectFactory"));
  30. //设置objectWrapperFactory配置
  31. objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
  32. //设置reflectFactory配置
  33. reflectorFactoryElement(root.evalNode("reflectorFactory"));
  34. settingsElement(settings);
  35. // read it after objectFactory and objectWrapperFactory issue #631
  36. //设置environments配置
  37. environmentsElement(root.evalNode("environments"));
  38. //设置databaseIdProvider配置
  39. databaseIdProviderElement(root.evalNode("databaseIdProvider"));
  40. //设置typeHandlers配置
  41. typeHandlerElement(root.evalNode("typeHandlers"));
  42. //设置mappers配置
  43. mapperElement(root.evalNode("mappers"));
  44. } catch (Exception e) {
  45. throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
  46. }
  47. }

可以看出parse的作用是解析mybatis-config.xml的configuration节点的内容,然后挨个赋值给configuration对象的属性。
而XMLConfigBuilder的其他私有方法都是给根据XNode对象(XML配置的configuration节点内容)来给全局配置变量configuration的属性进行赋值,关于Configuration类的解析下一章会解析

总结:XMLConfigBuilder类的作用是根据全局配置文件mybatis-config.xml的流文件进行解析,解析xml中的各个节点,然后创建一个Configuration对象,并将xml中的节点属性赋值给Configuration对象

6. Configuration 分析

Configuration类位于mybatis包的org.apache.ibatis.session目录下,是mybatis的全局变量,属性就是对应于mybatis的全局配置文件mybatis-config.xml的配置,将XML配置中的内容解析赋值到Configuration对象中。
由于XML配置项有很多,所以Configuration类的属性也很多。先来看下Configuration对于的XML配置文件示例:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
  3. <!-- 全局配置顶级节点 -->
  4. <configuration>
  5. <!-- 属性配置,读取properties中的配置文件 -->
  6. <properties resource="db.propertis">
  7. <property name="XXX" value="XXX"/>
  8. </properties>
  9. <!-- 类型别名 -->
  10. <typeAliases>
  11. <!-- 在用到User类型的时候,可以直接使用别名,不需要输入User类的全部路径 -->
  12. <typeAlias type="com.luck.codehelp.entity.User" alias="user"/>
  13. </typeAliases>
  14. <!-- 类型处理器 -->
  15. <typeHandlers>
  16. <!-- 类型处理器的作用是完成JDBC类型和java类型的转换,mybatis默认已经由了很多类型处理器,正常无需自定义-->
  17. </typeHandlers>
  18. <!-- 对象工厂 -->
  19. <!-- mybatis创建结果对象的新实例时,会通过对象工厂来完成,mybatis有默认的对象工厂,正常无需配置 -->
  20. <objectFactory type=""></objectFactory>
  21. <!-- 插件 -->
  22. <plugins>
  23. <!-- 可以自定义拦截器通过plugin标签加入 -->
  24. <plugin interceptor="com.lucky.interceptor.MyPlugin"></plugin>
  25. </plugins>
  26. <!-- 全局配置参数 -->
  27. <settings>
  28. <setting name="cacheEnabled" value="false" />
  29. <setting name="useGeneratedKeys" value="true" /><!-- 是否自动生成主键 -->
  30. <setting name="defaultExecutorType" value="REUSE" />
  31. <setting name="lazyLoadingEnabled" value="true"/><!-- 延迟加载标识 -->
  32. <setting name="aggressiveLazyLoading" value="true"/><!--有延迟加载属性的对象是否延迟加载 -->
  33. <setting name="multipleResultSetsEnabled" value="true"/><!-- 是否允许单个语句返回多个结果集 -->
  34. <setting name="useColumnLabel" value="true"/><!-- 使用列标签而不是列名 -->
  35. <setting name="autoMappingBehavior" value="PARTIAL"/><!-- 指定mybatis如何自动映射列到字段属性;NONE:自动映射;PARTIAL:只会映射结果没有嵌套的结果;FULL:可以映射任何复杂的结果 -->
  36. <setting name="defaultExecutorType" value="SIMPLE"/><!-- 默认执行器类型 -->
  37. <setting name="defaultFetchSize" value=""/>
  38. <setting name="defaultStatementTimeout" value="5"/><!-- 驱动等待数据库相应的超时时间 ,单位是秒-->
  39. <setting name="safeRowBoundsEnabled" value="false"/><!-- 是否允许使用嵌套语句RowBounds -->
  40. <setting name="safeResultHandlerEnabled" value="true"/>
  41. <setting name="mapUnderscoreToCamelCase" value="false"/><!-- 下划线列名是否自动映射到驼峰属性:如user_id映射到userId -->
  42. <setting name="localCacheScope" value="SESSION"/><!-- 本地缓存(session是会话级别) -->
  43. <setting name="jdbcTypeForNull" value="OTHER"/><!-- 数据为空值时,没有特定的JDBC类型的参数的JDBC类型 -->
  44. <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/><!-- 指定触发延迟加载的对象的方法 -->
  45. <setting name="callSettersOnNulls" value="false"/><!--如果setter方法或map的put方法,如果检索到的值为null时,数据是否有用 -->
  46. <setting name="logPrefix" value="XXXX"/><!-- mybatis日志文件前缀字符串 -->
  47. <setting name="logImpl" value="SLF4J"/><!-- mybatis日志的实现类 -->
  48. <setting name="proxyFactory" value="CGLIB"/><!-- mybatis代理工具 -->
  49. </settings>
  50. <!-- 环境配置集合 -->
  51. <environments default="development">
  52. <environment id="development">
  53. <transactionManager type="JDBC"/><!-- 事务管理器 -->
  54. <dataSource type="POOLED"><!-- 数据库连接池 -->
  55. <property name="driver" value="com.mysql.jdbc.Driver" />
  56. <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8" />
  57. <property name="username" value="root" />
  58. <property name="password" value="*****" />
  59. </dataSource>
  60. </environment>
  61. </environments>
  62. <!-- mapper文件映射配置 -->
  63. <mappers>
  64. <mapper resource="com/luck/codehelp/mapper/UserMapper.xml"/>
  65. </mappers>
  66. </configuration>

而对于XML的配置,Configuration类的属性是和XML配置对应的。Configuration类属性如下:

  1. protected Environment environment;
  2. protected boolean safeRowBoundsEnabled;
  3. protected boolean safeResultHandlerEnabled = true;
  4. protected boolean mapUnderscoreToCamelCase;
  5. //true:有延迟加载属性的对象被调用时完全加载任意属性;false:每个属性按需要加载
  6. protected boolean aggressiveLazyLoading;
  7. //是否允许多种结果集从一个单独的语句中返回
  8. protected boolean multipleResultSetsEnabled = true;
  9. //是否支持自动生成主键
  10. protected boolean useGeneratedKeys;
  11. //是否使用列标签
  12. protected boolean useColumnLabel = true;
  13. //是否使用缓存标识
  14. protected boolean cacheEnabled = true;
  15. protected boolean callSettersOnNulls;
  16. protected boolean useActualParamName = true;
  17. protected boolean returnInstanceForEmptyRow;
  18. protected boolean shrinkWhitespacesInSql;
  19. protected String logPrefix;
  20. protected Class<? extends Log> logImpl;
  21. protected Class<? extends VFS> vfsImpl;
  22. protected Class<?> defaultSqlProviderType;
  23. protected LocalCacheScope localCacheScope = LocalCacheScope.SESSION;
  24. protected JdbcType jdbcTypeForNull = JdbcType.OTHER;
  25. protected Set<String> lazyLoadTriggerMethods = new HashSet<>(Arrays.asList("equals", "clone", "hashCode", "toString"));
  26. protected Integer defaultStatementTimeout;
  27. protected Integer defaultFetchSize;
  28. protected ResultSetType defaultResultSetType;
  29. protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
  30. //指定mybatis如果自动映射列到字段和属性,PARTIAL会自动映射简单的没有嵌套的结果,FULL会自动映射任意复杂的结果
  31. protected AutoMappingBehavior autoMappingBehavior = AutoMappingBehavior.PARTIAL;
  32. protected AutoMappingUnknownColumnBehavior autoMappingUnknownColumnBehavior = AutoMappingUnknownColumnBehavior.NONE;
  33. protected Properties variables = new Properties();
  34. protected ReflectorFactory reflectorFactory = new DefaultReflectorFactory();
  35. protected ObjectFactory objectFactory = new DefaultObjectFactory();
  36. protected ObjectWrapperFactory objectWrapperFactory = new DefaultObjectWrapperFactory();
  37. //是否延时加载,false则表示所有关联对象即使加载,true表示延时加载
  38. protected boolean lazyLoadingEnabled = false;
  39. protected ProxyFactory proxyFactory = new JavassistProxyFactory(); // #224 Using internal Javassist instead of OGNL
  40. protected String databaseId;
  41. /**
  42. * Configuration factory class.
  43. * Used to create Configuration for loading deserialized unread properties.
  44. *
  45. * @see <a href='https://github.com/mybatis/old-google-code-issues/issues/300'>Issue 300 (google code)</a>
  46. */
  47. protected Class<?> configurationFactory;
  48. protected final MapperRegistry mapperRegistry = new MapperRegistry(this);
  49. protected final InterceptorChain interceptorChain = new InterceptorChain();
  50. protected final TypeHandlerRegistry typeHandlerRegistry = new TypeHandlerRegistry(this);
  51. protected final TypeAliasRegistry typeAliasRegistry = new TypeAliasRegistry();
  52. protected final LanguageDriverRegistry languageRegistry = new LanguageDriverRegistry();
  53. protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection")
  54. .conflictMessageProducer((savedValue, targetValue) ->
  55. ". please check " + savedValue.getResource() + " and " + targetValue.getResource());
  56. protected final Map<String, Cache> caches = new StrictMap<>("Caches collection");
  57. protected final Map<String, ResultMap> resultMaps = new StrictMap<>("Result Maps collection");
  58. protected final Map<String, ParameterMap> parameterMaps = new StrictMap<>("Parameter Maps collection");
  59. protected final Map<String, KeyGenerator> keyGenerators = new StrictMap<>("Key Generators collection");
  60. //已经加载过的resource(mapper)
  61. protected final Set<String> loadedResources = new HashSet<>();
  62. protected final Map<String, XNode> sqlFragments = new StrictMap<>("XML fragments parsed from previous mappers");
  63. protected final Collection<XMLStatementBuilder> incompleteStatements = new LinkedList<>();
  64. protected final Collection<CacheRefResolver> incompleteCacheRefs = new LinkedList<>();
  65. protected final Collection<ResultMapResolver> incompleteResultMaps = new LinkedList<>();
  66. protected final Collection<MethodResolver> incompleteMethods = new LinkedList<>();
  67. /*
  68. * A map holds cache-ref relationship. The key is the namespace that
  69. * references a cache bound to another namespace and the value is the
  70. * namespace which the actual cache is bound to.
  71. */
  72. protected final Map<String, String> cacheRefMap = new HashMap<>();

而Configuration中的方法也差不多都是关于这些属性的set和get方法。由于属性太多,就不一一解析,现在只知道Configuration类是和mybatis的XML配置是对应的。加载的过程是SqlSessionFactoryBuilder根据xml配置的文件流,通过XMLConfigBuilder的parse方法进行解析得到一个Configuration对象。那么Configuration什么时候会用到呢?

7. SqlSession 分析

mybatis启动的时候会加载XML配置文件解析生成全局配置对象Configuration对象,SqlSessionFactoryBuilder类会根据Configuration对象创建一个DefaultSqlSessionFactory对象,而DefaultSqlSessionFactory对象实现了SqlSessionFactory中的创建SqlSession的方法,最终新建了一个SqlSession接口的默认实现类DefaultSqlSession,现在先来了解下SqlSession以及它的实现类
SqlSession解析
SqlSession位于mybatis包的org.apache.ibatis.session目录下,字面意思就是sql的会话,用于程序和数据库直接的sql会话,程序执行一次数据库操作就需要创建一个sqlSession,操作结束即关闭sqlSession;
既然是程序和数据库之间的会话,那么sqlSession接口的方法应该是程序和数据库都容易理解的,sqlSession中定义的方法都是关于数据库操作的方法,源码如下:

  1. package org.apache.ibatis.session;
  2. import java.io.Closeable;
  3. import java.sql.Connection;
  4. import java.util.List;
  5. import java.util.Map;
  6. import org.apache.ibatis.cursor.Cursor;
  7. import org.apache.ibatis.executor.BatchResult;
  8. public interface SqlSession extends Closeable {
  9. //根据Sql语句查询单条记录
  10. <T> T selectOne(String statement);
  11. <T> T selectOne(String statement, Object parameter);//根据Sql语句和参数查询单条记录
  12. //根据Sql语句查询多条记录
  13. <E> List<E> selectList(String statement);
  14. <E> List<E> selectList(String statement, Object parameter);//根据Sql语句和参数查询多条记录
  15. <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds);//根据Sql语句和参数以及分页参数查询多条记录
  16. //selectMap和selectList原理一样,只是将结果集映射成Map对象返回
  17. <K, V> Map<K, V> selectMap(String statement, String mapKey);
  18. <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey);
  19. <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds);
  20. //返回游标对象
  21. <T> Cursor<T> selectCursor(String statement);
  22. <T> Cursor<T> selectCursor(String statement, Object parameter);
  23. <T> Cursor<T> selectCursor(String statement, Object parameter, RowBounds rowBounds);
  24. //查询的结果对象由指定的ResultHandler处理
  25. void select(String statement, Object parameter, ResultHandler handler);
  26. void select(String statement, ResultHandler handler);
  27. void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler);
  28. //执行insert语句
  29. int insert(String statement);
  30. int insert(String statement, Object parameter);
  31. //执行update语句
  32. int update(String statement);
  33. int update(String statement, Object parameter);
  34. //执行delete语句
  35. int delete(String statement);
  36. int delete(String statement, Object parameter);
  37. //提交事务
  38. void commit();
  39. void commit(boolean force);
  40. //事务回滚
  41. void rollback();
  42. void rollback(boolean force);
  43. //将请求刷新到数据库
  44. List<BatchResult> flushStatements();
  45. //关闭sqlSession
  46. @Override
  47. void close();
  48. //清除缓存
  49. void clearCache();
  50. //获取Configuration对象
  51. Configuration getConfiguration();
  52. //获取Type对象的Mapper对象
  53. <T> T getMapper(Class<T> type);
  54. //获取sqlSession对象的数据库连接
  55. Connection getConnection();
  56. }

SqlSession中的方法全是和数据库相关的增删改查以及事务的提交方法。
SqlSession有三个实现类,除了默认的DefaultSqlSession之外,还有SqlSessionManager和SqlSessionTemplate
接下来先看下SqlSession默认的实现类DefaultSqlSession是如何实现的。

7.1. DefaultSqlSession

DefaultSqlSession有5个属性和2个构造方法如下:

  1. //全局配置
  2. private final Configuration configuration;
  3. //执行器
  4. private final Executor executor;
  5. //自动提交标识
  6. private final boolean autoCommit;
  7. private boolean dirty;
  8. //游标列表
  9. private List<Cursor<?>> cursorList;
  10. /**
  11. * 构造方法
  12. * @param configuration
  13. * @param executor
  14. * @param autoCommit
  15. */
  16. public DefaultSqlSession(Configuration configuration, Executor executor, boolean autoCommit) {
  17. this.configuration = configuration;
  18. this.executor = executor;
  19. this.dirty = false;
  20. this.autoCommit = autoCommit;
  21. }
  22. /**
  23. * 构造方法
  24. * @param configuration
  25. * @param executor
  26. */
  27. public DefaultSqlSession(Configuration configuration, Executor executor) {
  28. this(configuration, executor, false);
  29. }

以selectOne()方法为例

  1. @Override
  2. public <T> T selectOne(String statement) {
  3. return this.<T>selectOne(statement, null);
  4. }
  5. @Override
  6. public <T> T selectOne(String statement, Object parameter) {
  7. // Popular vote was to return null on 0 results and throw exception on too many.
  8. List<T> list = this.<T>selectList(statement, parameter);
  9. if (list.size() == 1) {
  10. return list.get(0);
  11. } else if (list.size() > 1) {
  12. throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
  13. } else {
  14. return null;
  15. }
  16. }

selectOne()最终都是调用了selectList方法,然后取唯一的一条数据返回。那在看看selectList相关的代码

  1. @Override
  2. public <E> List<E> selectList(String statement) {
  3. return this.selectList(statement, null);
  4. }
  5. @Override
  6. public <E> List<E> selectList(String statement, Object parameter) {
  7. return this.selectList(statement, parameter, RowBounds.DEFAULT);
  8. }
  9. @Override
  10. public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
  11. try {
  12. MappedStatement ms = configuration.getMappedStatement(statement);
  13. return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
  14. } catch (Exception e) {
  15. throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
  16. } finally {
  17. ErrorContext.instance().reset();
  18. }
  19. }

共有三个selectList()方法,最终都是调用了最后一个selectList()方法,这里有三个参数:statement是sql语句、
parameter是传入的参数、RowBounds是和分页相关的参数
RowBounds源码如下:

  1. package org.apache.ibatis.session;
  2. /**
  3. * @author Clinton Begin
  4. */
  5. public class RowBounds {
  6. public static final int NO_ROW_OFFSET = 0;
  7. public static final int NO_ROW_LIMIT = Integer.MAX_VALUE; //int的最大值
  8. public static final RowBounds DEFAULT = new RowBounds();
  9. private int offset;
  10. private int limit;
  11. public RowBounds() {
  12. this.offset = NO_ROW_OFFSET;
  13. this.limit = NO_ROW_LIMIT;
  14. }
  15. public RowBounds(int offset, int limit) {
  16. this.offset = offset;
  17. this.limit = limit;
  18. }
  19. public int getOffset() {
  20. return offset;
  21. }
  22. public int getLimit() {
  23. return limit;
  24. }
  25. }

RowBounds的两个属性:offSet是指查询数据时从多少位置开始查询,limit是指返回数据的调试,默认是从0位置开始查询到Integer的最大值,默认是不做分页处理。
在selectList()执行如下:

  1. public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
  2. try {
  3. // 获取MappedStatment对象
  4. MappedStatement ms = configuration.getMappedStatement(statement);
  5. // 通过执行器查询数据结果
  6. return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
  7. } catch (Exception e) {
  8. throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
  9. } finally {
  10. ErrorContext.instance().reset();
  11. }
  12. }

前面讲了数据是如何查询的,我们在看看其他的insert、update、delete方法

  1. @Override
  2. public int insert(String statement) {
  3. return insert(statement, null);
  4. }
  5. @Override
  6. public int insert(String statement, Object parameter) {
  7. return update(statement, parameter);
  8. }
  9. @Override
  10. public int update(String statement) {
  11. return update(statement, null);
  12. }
  13. @Override
  14. public int update(String statement, Object parameter) {
  15. try {
  16. dirty = true;
  17. MappedStatement ms = configuration.getMappedStatement(statement);
  18. return executor.update(ms, wrapCollection(parameter));
  19. } catch (Exception e) {
  20. throw ExceptionFactory.wrapException("Error updating database. Cause: " + e, e);
  21. } finally {
  22. ErrorContext.instance().reset();
  23. }
  24. }
  25. @Override
  26. public int delete(String statement) {
  27. return update(statement, null);
  28. }
  29. @Override
  30. public int delete(String statement, Object parameter) {
  31. return update(statement, parameter);
  32. }

可以看出SqlSession的insert和delete的方法最终都是调用了update方法,而update方法最终也是调用了Executor的update由此可得出结论sqlSession虽然叫程序和数据库之间的SQL会话,但是它并没有具体去执行sql语句,最终的sql语句的执行是由执行器Executor执行的,而SqlSession的作用只是创建了MappedStatement对象以及调用执行器去执行SQL其他的commit、rollback方法同样最终都是调用的执行器Executor的对应的方法,那么接下来就去了解下执行器Executor是如何执行的,以及SqlSession创建的MappedStatement又是什么?
DefaultSqlSession完整源码如下:

  1. /**
  2. * Copyright 2009-2015 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.apache.ibatis.session.defaults;
  17. import java.io.IOException;
  18. import java.sql.Connection;
  19. import java.sql.SQLException;
  20. import java.util.ArrayList;
  21. import java.util.Collection;
  22. import java.util.HashMap;
  23. import java.util.List;
  24. import java.util.Map;
  25. import org.apache.ibatis.binding.BindingException;
  26. import org.apache.ibatis.cursor.Cursor;
  27. import org.apache.ibatis.exceptions.ExceptionFactory;
  28. import org.apache.ibatis.exceptions.TooManyResultsException;
  29. import org.apache.ibatis.executor.BatchResult;
  30. import org.apache.ibatis.executor.ErrorContext;
  31. import org.apache.ibatis.executor.Executor;
  32. import org.apache.ibatis.executor.result.DefaultMapResultHandler;
  33. import org.apache.ibatis.executor.result.DefaultResultContext;
  34. import org.apache.ibatis.mapping.MappedStatement;
  35. import org.apache.ibatis.session.Configuration;
  36. import org.apache.ibatis.session.ResultHandler;
  37. import org.apache.ibatis.session.RowBounds;
  38. import org.apache.ibatis.session.SqlSession;
  39. /**
  40. *
  41. * The default implementation for {@link SqlSession}.
  42. * Note that this class is not Thread-Safe.
  43. *
  44. * @author Clinton Begin
  45. */
  46. public class DefaultSqlSession implements SqlSession {
  47. private Configuration configuration;
  48. private Executor executor;
  49. private boolean autoCommit;
  50. private boolean dirty;
  51. private List<Cursor<?>> cursorList;
  52. public DefaultSqlSession(Configuration configuration, Executor executor, boolean autoCommit) {
  53. this.configuration = configuration;
  54. this.executor = executor;
  55. this.dirty = false;
  56. this.autoCommit = autoCommit;
  57. }
  58. public DefaultSqlSession(Configuration configuration, Executor executor) {
  59. this(configuration, executor, false);
  60. }
  61. @Override
  62. public <T> T selectOne(String statement) {
  63. return this.<T>selectOne(statement, null);
  64. }
  65. @Override
  66. public <T> T selectOne(String statement, Object parameter) {
  67. // Popular vote was to return null on 0 results and throw exception on too many.
  68. List<T> list = this.<T>selectList(statement, parameter);
  69. if (list.size() == 1) {
  70. return list.get(0);
  71. } else if (list.size() > 1) {
  72. throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
  73. } else {
  74. return null;
  75. }
  76. }
  77. @Override
  78. public <K, V> Map<K, V> selectMap(String statement, String mapKey) {
  79. return this.selectMap(statement, null, mapKey, RowBounds.DEFAULT);
  80. }
  81. @Override
  82. public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey) {
  83. return this.selectMap(statement, parameter, mapKey, RowBounds.DEFAULT);
  84. }
  85. @Override
  86. public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) {
  87. final List<? extends V> list = selectList(statement, parameter, rowBounds);
  88. final DefaultMapResultHandler<K, V> mapResultHandler = new DefaultMapResultHandler<K, V>(mapKey,
  89. configuration.getObjectFactory(), configuration.getObjectWrapperFactory(), configuration.getReflectorFactory());
  90. final DefaultResultContext<V> context = new DefaultResultContext<V>();
  91. for (V o : list) {
  92. context.nextResultObject(o);
  93. mapResultHandler.handleResult(context);
  94. }
  95. return mapResultHandler.getMappedResults();
  96. }
  97. @Override
  98. public <T> Cursor<T> selectCursor(String statement) {
  99. return selectCursor(statement, null);
  100. }
  101. @Override
  102. public <T> Cursor<T> selectCursor(String statement, Object parameter) {
  103. return selectCursor(statement, parameter, RowBounds.DEFAULT);
  104. }
  105. @Override
  106. public <T> Cursor<T> selectCursor(String statement, Object parameter, RowBounds rowBounds) {
  107. try {
  108. MappedStatement ms = configuration.getMappedStatement(statement);
  109. Cursor<T> cursor = executor.queryCursor(ms, wrapCollection(parameter), rowBounds);
  110. registerCursor(cursor);
  111. return cursor;
  112. } catch (Exception e) {
  113. throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
  114. } finally {
  115. ErrorContext.instance().reset();
  116. }
  117. }
  118. @Override
  119. public <E> List<E> selectList(String statement) {
  120. return this.selectList(statement, null);
  121. }
  122. @Override
  123. public <E> List<E> selectList(String statement, Object parameter) {
  124. return this.selectList(statement, parameter, RowBounds.DEFAULT);
  125. }
  126. @Override
  127. public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
  128. try {
  129. MappedStatement ms = configuration.getMappedStatement(statement);
  130. return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
  131. } catch (Exception e) {
  132. throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
  133. } finally {
  134. ErrorContext.instance().reset();
  135. }
  136. }
  137. @Override
  138. public void select(String statement, Object parameter, ResultHandler handler) {
  139. select(statement, parameter, RowBounds.DEFAULT, handler);
  140. }
  141. @Override
  142. public void select(String statement, ResultHandler handler) {
  143. select(statement, null, RowBounds.DEFAULT, handler);
  144. }
  145. @Override
  146. public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
  147. try {
  148. MappedStatement ms = configuration.getMappedStatement(statement);
  149. executor.query(ms, wrapCollection(parameter), rowBounds, handler);
  150. } catch (Exception e) {
  151. throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
  152. } finally {
  153. ErrorContext.instance().reset();
  154. }
  155. }
  156. @Override
  157. public int insert(String statement) {
  158. return insert(statement, null);
  159. }
  160. @Override
  161. public int insert(String statement, Object parameter) {
  162. return update(statement, parameter);
  163. }
  164. @Override
  165. public int update(String statement) {
  166. return update(statement, null);
  167. }
  168. @Override
  169. public int update(String statement, Object parameter) {
  170. try {
  171. dirty = true;
  172. MappedStatement ms = configuration.getMappedStatement(statement);
  173. return executor.update(ms, wrapCollection(parameter));
  174. } catch (Exception e) {
  175. throw ExceptionFactory.wrapException("Error updating database. Cause: " + e, e);
  176. } finally {
  177. ErrorContext.instance().reset();
  178. }
  179. }
  180. @Override
  181. public int delete(String statement) {
  182. return update(statement, null);
  183. }
  184. @Override
  185. public int delete(String statement, Object parameter) {
  186. return update(statement, parameter);
  187. }
  188. @Override
  189. public void commit() {
  190. commit(false);
  191. }
  192. @Override
  193. public void commit(boolean force) {
  194. try {
  195. executor.commit(isCommitOrRollbackRequired(force));
  196. dirty = false;
  197. } catch (Exception e) {
  198. throw ExceptionFactory.wrapException("Error committing transaction. Cause: " + e, e);
  199. } finally {
  200. ErrorContext.instance().reset();
  201. }
  202. }
  203. @Override
  204. public void rollback() {
  205. rollback(false);
  206. }
  207. @Override
  208. public void rollback(boolean force) {
  209. try {
  210. executor.rollback(isCommitOrRollbackRequired(force));
  211. dirty = false;
  212. } catch (Exception e) {
  213. throw ExceptionFactory.wrapException("Error rolling back transaction. Cause: " + e, e);
  214. } finally {
  215. ErrorContext.instance().reset();
  216. }
  217. }
  218. @Override
  219. public List<BatchResult> flushStatements() {
  220. try {
  221. return executor.flushStatements();
  222. } catch (Exception e) {
  223. throw ExceptionFactory.wrapException("Error flushing statements. Cause: " + e, e);
  224. } finally {
  225. ErrorContext.instance().reset();
  226. }
  227. }
  228. @Override
  229. public void close() {
  230. try {
  231. executor.close(isCommitOrRollbackRequired(false));
  232. closeCursors();
  233. dirty = false;
  234. } finally {
  235. ErrorContext.instance().reset();
  236. }
  237. }
  238. private void closeCursors() {
  239. if (cursorList != null && cursorList.size() != 0) {
  240. for (Cursor<?> cursor : cursorList) {
  241. try {
  242. cursor.close();
  243. } catch (IOException e) {
  244. throw ExceptionFactory.wrapException("Error closing cursor. Cause: " + e, e);
  245. }
  246. }
  247. cursorList.clear();
  248. }
  249. }
  250. @Override
  251. public Configuration getConfiguration() {
  252. return configuration;
  253. }
  254. @Override
  255. public <T> T getMapper(Class<T> type) {
  256. return configuration.<T>getMapper(type, this);
  257. }
  258. @Override
  259. public Connection getConnection() {
  260. try {
  261. return executor.getTransaction().getConnection();
  262. } catch (SQLException e) {
  263. throw ExceptionFactory.wrapException("Error getting a new connection. Cause: " + e, e);
  264. }
  265. }
  266. @Override
  267. public void clearCache() {
  268. executor.clearLocalCache();
  269. }
  270. private <T> void registerCursor(Cursor<T> cursor) {
  271. if (cursorList == null) {
  272. cursorList = new ArrayList<Cursor<?>>();
  273. }
  274. cursorList.add(cursor);
  275. }
  276. private boolean isCommitOrRollbackRequired(boolean force) {
  277. return (!autoCommit && dirty) || force;
  278. }
  279. private Object wrapCollection(final Object object) {
  280. if (object instanceof Collection) {
  281. StrictMap<Object> map = new StrictMap<Object>();
  282. map.put("collection", object);
  283. if (object instanceof List) {
  284. map.put("list", object);
  285. }
  286. return map;
  287. } else if (object != null && object.getClass().isArray()) {
  288. StrictMap<Object> map = new StrictMap<Object>();
  289. map.put("array", object);
  290. return map;
  291. }
  292. return object;
  293. }
  294. public static class StrictMap<V> extends HashMap<String, V> {
  295. private static final long serialVersionUID = -5741767162221585340L;
  296. @Override
  297. public V get(Object key) {
  298. if (!super.containsKey(key)) {
  299. throw new BindingException("Parameter '" + key + "' not found. Available parameters are " + this.keySet());
  300. }
  301. return super.get(key);
  302. }
  303. }
  304. }

8. MappedStatement 分析

MappedStatement类位于mybatis包的org.apache.ibatis.mapping目录下,是一个final类型也就是说实例化之后就不允许改变MappedStatement对象对应Mapper.xml配置文件中的一个select/update/insert/delete节点,描述的就是一条SQL语句,属性如下:

  1. //mapper配置文件名,如:UserMapper.xml
  2. private String resource;
  3. //全局配置
  4. private Configuration configuration;
  5. //Mapper.xml文件中节点的id属性加命名空间,如:com.lucky.mybatis.dao.UserMapper.selectByExample
  6. private String id;
  7. private Integer fetchSize;
  8. //超时时间
  9. private Integer timeout;
  10. //操作SQL的对象的类型
  11. private StatementType statementType;
  12. //结果类型
  13. private ResultSetType resultSetType;
  14. //sql语句
  15. private SqlSource sqlSource;
  16. //缓存
  17. private Cache cache;
  18. private ParameterMap parameterMap;
  19. private List<ResultMap> resultMaps;
  20. private boolean flushCacheRequired;
  21. //是否使用缓存,默认为true
  22. private boolean useCache;
  23. //结果是否排序
  24. private boolean resultOrdered;
  25. //sql语句的类型,如select、update、delete、insert
  26. private SqlCommandType sqlCommandType;
  27. private KeyGenerator keyGenerator;
  28. private String[] keyProperties;
  29. private String[] keyColumns;
  30. private boolean hasNestedResultMaps;
  31. //数据库ID
  32. private String databaseId;
  33. private Log statementLog;
  34. private LanguageDriver lang;
  35. private String[] resultSets;

StatementType指操作SQL对象的类型,是个枚举类型,值分别为:

  • STATEMENT(直接操作SQL,不进行预编译),
  • PREPARED(预处理参数,进行预编译,获取数据),
  • CALLABLE(执行存储过程)

ResultSetType指返回结果集的类型,也是个枚举类型,值分别为:

  • FORWARD_ONLY:结果集的游标只能向下滚动
  • SCROLL_INSENSITIVE:结果集的游标可以上下移动,当数据库变化时当前结果集不变
  • SCROLL_SENSITIVE:结果集客自由滚动,数据库变化时当前结果集同步改变

现在我们知道一个MappedStatement对象对应一个mapper.xml中的一个SQL节点,而Mapper.xml文件是初始化Configuration对象的时候进行解析加载的,则说明MappedStatement对象就是在初始化Configuration对象的时候创建的,并且是final类型不可更改。
之前我们知道Configuration对象的初始化过程,是通过XMLConfigBuilder类的parse方法进行初始化的,现在来看下是如何初始化MappedStatement对象的和Configuration对象初始化代码如下:

8.1. 创建Configuration对象

  1. /**
  2. * 在SqlSessionFactoryBuilder类中调用
  3. */
  4. private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {
  5. // 创建Configuration对象,此时的Configuration对象没有任何内容,仅仅是创建这么个对象
  6. super(new Configuration());
  7. ErrorContext.instance().resource("SQL Mapper Configuration");
  8. this.configuration.setVariables(props);
  9. this.parsed = false;
  10. this.environment = environment;
  11. this.parser = parser;
  12. }
  13. public Configuration parse() {
  14. //判断Configuration是否解析过,Configuration是全局变量,只需要解析创建一次即可
  15. if (parsed) {
  16. throw new BuilderException("Each XMLConfigBuilder can only be used once.");
  17. }
  18. parsed = true;
  19. //调用下面的方法,parser.evalNode("/configuration")解析XML配置得到XNode对象
  20. //parseConfiguration 为Configuration对象赋值
  21. parseConfiguration(parser.evalNode("/configuration"));
  22. // 返回Configuration对象
  23. return configuration;
  24. }
  25. /**
  26. * 根据root中存储的是configuration节点的内容
  27. * @param root
  28. */
  29. private void parseConfiguration(XNode root) {
  30. try {
  31. // issue #117 read properties first
  32. //设置properties配置
  33. propertiesElement(root.evalNode("properties"));
  34. //设置settings配置
  35. Properties settings = settingsAsProperties(root.evalNode("settings"));
  36. loadCustomVfs(settings);
  37. loadCustomLogImpl(settings);
  38. //设置typeAliases配置
  39. typeAliasesElement(root.evalNode("typeAliases"));
  40. //设置plugins配置
  41. pluginElement(root.evalNode("plugins"));
  42. //设置objectFactory配置
  43. objectFactoryElement(root.evalNode("objectFactory"));
  44. //设置objectWrapperFactory配置
  45. objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
  46. //设置reflectFactory配置
  47. reflectorFactoryElement(root.evalNode("reflectorFactory"));
  48. settingsElement(settings);
  49. // read it after objectFactory and objectWrapperFactory issue #631
  50. //设置environments配置
  51. environmentsElement(root.evalNode("environments"));
  52. //设置databaseIdProvider配置
  53. databaseIdProviderElement(root.evalNode("databaseIdProvider"));
  54. //设置typeHandlers配置
  55. typeHandlerElement(root.evalNode("typeHandlers"));
  56. //设置mappers配置
  57. mapperElement(root.evalNode("mappers"));
  58. } catch (Exception e) {
  59. throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
  60. }
  61. }

8.2. 解析xxxMapper.xml文件

parseConfiguration()方法是根据XNode对Configuration对象进行属性赋值,mapperElement()方法即解析标签中的内容,mapperElement()方法源码如下:

  1. private void mapperElement(XNode parent) throws Exception {
  2. //parent是Configuration配置文件中的<mappers>标签
  3. if (parent != null) {
  4. //遍历<mappers>标签下的所有子标签
  5. for (XNode child : parent.getChildren()) {
  6. if ("package".equals(child.getName())) {
  7. //加载package包下的所有mapper
  8. String mapperPackage = child.getStringAttribute("name");
  9. configuration.addMappers(mapperPackage);//加载packege包下的所有mapper
  10. } else {
  11. //按resource或url或class加载单个mapper
  12. String resource = child.getStringAttribute("resource");
  13. String url = child.getStringAttribute("url");
  14. String mapperClass = child.getStringAttribute("class");
  15. if (resource != null && url == null && mapperClass == null) {
  16. ErrorContext.instance().resource(resource);
  17. InputStream inputStream = Resources.getResourceAsStream(resource);
  18. XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
  19. mapperParser.parse();//解析xml文件流
  20. } else if (resource == null && url != null && mapperClass == null) {
  21. ErrorContext.instance().resource(url);
  22. InputStream inputStream = Resources.getUrlAsStream(url);
  23. XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
  24. mapperParser.parse();//解析xml文件流
  25. } else if (resource == null && url == null && mapperClass != null) {
  26. Class<?> mapperInterface = Resources.classForName(mapperClass);
  27. configuration.addMapper(mapperInterface);//加载指定接口的mapper
  28. } else {
  29. throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
  30. }
  31. }
  32. }
  33. }
  34. }

mapperElement()方法有三种方式加载mapper,一个是批量加载指定package下所有mapper,一个是根据mapper接口路径加载指定mapper,还有一种是解析mapper.xml文件流进行加载

8.3. 初始化MappedStatement

先来看个最简单的,根据指定接口加载mapper,也就是configuration.addMapper(mapperInterface)方法,源码如下:
addMapper()方法

  1. public <T> void addMapper(Class<T> type) {
  2. mapperRegistry.addMapper(type);
  3. }

调用了mapperRegistry的addMapper方法。mapperRegistry是Configuration类的一个属性

  1. protected final MapperRegistry mapperRegistry = new MapperRegistry(this);

根据MapperRegistry的名字可以理解为此类的作用是mapper的注册中心,用于注册mapper,MapperRegistry类源码如下:

  1. package org.apache.ibatis.binding;
  2. import org.apache.ibatis.builder.annotation.MapperAnnotationBuilder;
  3. import org.apache.ibatis.io.ResolverUtil;
  4. import org.apache.ibatis.session.Configuration;
  5. import org.apache.ibatis.session.SqlSession;
  6. import java.util.Collection;
  7. import java.util.Collections;
  8. import java.util.HashMap;
  9. import java.util.Map;
  10. import java.util.Set;
  11. public class MapperRegistry {
  12. //...省略代码
  13. //新增一个mapper
  14. public <T> void addMapper(Class<T> type) {
  15. if (type.isInterface()) {
  16. if (hasMapper(type)) {
  17. throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
  18. }
  19. boolean loadCompleted = false;
  20. try {
  21. //加载指定的mapper接口
  22. knownMappers.put(type, new MapperProxyFactory<T>(type));
  23. // It's important that the type is added before the parser is run
  24. // otherwise the binding may automatically be attempted by the
  25. // mapper parser. If the type is already known, it won't try.
  26. MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
  27. 解析
  28. parser.parse();
  29. loadCompleted = true;
  30. } finally {
  31. if (!loadCompleted) {
  32. knownMappers.remove(type);
  33. }
  34. }
  35. }
  36. }
  37. // 省略代码
  38. }

看MapperAnnotationBuilder(mapper注解构造类)MapperAnnotationBuilder类的构造方法如下:

  1. public MapperAnnotationBuilder(Configuration configuration, Class<?> type) {
  2. String resource = type.getName().replace('.', '/') + ".java (best guess)";
  3. this.assistant = new MapperBuilderAssistant(configuration, resource);
  4. this.configuration = configuration;
  5. this.type = type;
  6. sqlAnnotationTypes.add(Select.class);
  7. sqlAnnotationTypes.add(Insert.class);
  8. sqlAnnotationTypes.add(Update.class);
  9. sqlAnnotationTypes.add(Delete.class);
  10. sqlProviderAnnotationTypes.add(SelectProvider.class);
  11. sqlProviderAnnotationTypes.add(InsertProvider.class);
  12. sqlProviderAnnotationTypes.add(UpdateProvider.class);
  13. sqlProviderAnnotationTypes.add(DeleteProvider.class);
  14. }

MapperAnnotationBuilder类的主要属性有:

  1. private final Set<Class<? extends Annotation>> sqlAnnotationTypes = new HashSet<Class<? extends Annotation>>();//sql语句上的注解
  2. private final Set<Class<? extends Annotation>> sqlProviderAnnotationTypes = new HashSet<Class<? extends Annotation>>();//指定类指定方法上的sql语句注解
  3. private Configuration configuration;//全局配置对象
  4. private MapperBuilderAssistant assistant;//Mapper构建助手类,组装解析出来的配置,生成Cache、ResultMap以及MappedStatement对象
  5. private Class<?> type;//解析的目标mapper接口的Class对象

MapperAnnotationBuilder构造方法就是给自己的属性进行了初始化,其中两个Set集合在初始化时表明了支持 @Select、@Insert、@Update、@Delete以及对应的Provider注解,本篇不再介绍,和xml配置的写法只是写法上不一样而已,实际的作用是一样,本文只分析xml这种用法。MapperAnnotationBuilder有一个parse()方法,也是创建MappedStatement的方法,源码如下:

  1. public void parse() {
  2. //mapper接口名,如:interface com.lucky.test.mapper.UserMapper
  3. String resource = type.toString();
  4. //Configuration中Set<String> loadedResources 保存着已经加载过的mapper信息
  5. //判断是否已经加载过
  6. if (!configuration.isResourceLoaded(resource)) {
  7. //加载XML资源
  8. loadXmlResource();
  9. //加载的resource添加到Configuration的loadedResources中
  10. configuration.addLoadedResource(resource);
  11. assistant.setCurrentNamespace(type.getName());
  12. parseCache();
  13. parseCacheRef();
  14. //遍历mapper的所有方法
  15. for (Method method : type.getMethods()) {
  16. if (!canHaveStatement(method)) {
  17. continue;
  18. }
  19. if (getAnnotationWrapper(method, false, Select.class, SelectProvider.class).isPresent()
  20. && method.getAnnotation(ResultMap.class) == null) {
  21. parseResultMap(method);
  22. }
  23. try {
  24. //
  25. parseStatement(method);
  26. } catch (IncompleteElementException e) {
  27. configuration.addIncompleteMethod(new MethodResolver(this, method));
  28. }
  29. }
  30. }
  31. parsePendingMethods();
  32. }

xxxMapper.xml文件的加载是通过调用loadXmlResource()方法加载的,源码如下:

  1. private void loadXmlResource() {
  2. // Spring may not know the real resource name so we check a flag
  3. // to prevent loading again a resource twice
  4. // this flag is set at XMLMapperBuilder#bindMapperForNamespace
  5. if (!configuration.isResourceLoaded("namespace:" + type.getName())) {
  6. //通过mapper接口名找到对应的mapper.xml路径
  7. String xmlResource = type.getName().replace('.', '/') + ".xml";
  8. // #1347
  9. InputStream inputStream = type.getResourceAsStream("/" + xmlResource);
  10. if (inputStream == null) {
  11. // Search XML mapper that is not in the module but in the classpath.
  12. try {
  13. //读取mapper.xml文件流
  14. inputStream = Resources.getResourceAsStream(type.getClassLoader(), xmlResource);
  15. } catch (IOException e2) {
  16. // ignore, resource is not required
  17. }
  18. }
  19. if (inputStream != null) {
  20. //根据mapper.xml文件流创建XMLMapperBuilder对象
  21. XMLMapperBuilder xmlParser = new XMLMapperBuilder(inputStream, assistant.getConfiguration(), xmlResource, configuration.getSqlFragments(), type.getName());
  22. //执行parse方法
  23. xmlParser.parse();
  24. }
  25. }
  26. }

解析xxxMapper.xml文件后封装为XMLMapperBuilder对象,它是mapper.xml构建者类,构造方法源码如下

  1. public XMLMapperBuilder(InputStream inputStream, Configuration configuration, String resource, Map<String, XNode> sqlFragments, String namespace) {
  2. //调用下面一个构造方法
  3. this(inputStream, configuration, resource, sqlFragments);
  4. this.builderAssistant.setCurrentNamespace(namespace);
  5. }
  6. public XMLMapperBuilder(InputStream inputStream, Configuration configuration, String resource, Map<String, XNode> sqlFragments) {
  7. //调用下面一个构造方法
  8. this(new XPathParser(inputStream, true, configuration.getVariables(), new XMLMapperEntityResolver()),
  9. configuration, resource, sqlFragments);
  10. }
  11. private XMLMapperBuilder(XPathParser parser, Configuration configuration, String resource, Map<String, XNode> sqlFragments) {
  12. //对自己的属性进行赋值
  13. super(configuration);
  14. //mapper构造者助手
  15. this.builderAssistant = new MapperBuilderAssistant(configuration, resource);
  16. //XML解析类
  17. this.parser = parser;
  18. //sql片段集合
  19. this.sqlFragments = sqlFragments;
  20. //mapper名称
  21. this.resource = resource;
  22. }

那么再看XMLMapperBuilder类的parse()方法,源码如下:

  1. public void parse() {
  2. if (!configuration.isResourceLoaded(resource)) {
  3. //从XML解析类中获取mapper标签的内容
  4. configurationElement(parser.evalNode("/mapper"));
  5. //将加载过的resource添加到Configuration中
  6. configuration.addLoadedResource(resource);
  7. //绑定mapper到对应mapper的命名空间中
  8. bindMapperForNamespace();
  9. }
  10. parsePendingResultMaps();
  11. parsePendingCacheRefs();
  12. parsePendingStatements();
  13. }

解析xml的主要方法就是configurationElement()方法,源码如下:

  1. private void configurationElement(XNode context) {
  2. try {
  3. //从xml中获取namespace标签内容
  4. String namespace = context.getStringAttribute("namespace");
  5. if (namespace == null || namespace.isEmpty()) {
  6. throw new BuilderException("Mapper's namespace cannot be empty");
  7. }
  8. builderAssistant.setCurrentNamespace(namespace);
  9. //获取cache-ref标签内容
  10. cacheRefElement(context.evalNode("cache-ref"));
  11. //获取cache标签内容
  12. cacheElement(context.evalNode("cache"));
  13. //获取parameterMap内容
  14. parameterMapElement(context.evalNodes("/mapper/parameterMap"));
  15. //获取resultMap内容
  16. resultMapElements(context.evalNodes("/mapper/resultMap"));
  17. //获取sql标签内容
  18. sqlElement(context.evalNodes("/mapper/sql"));
  19. //解析获取各种sql语句标签内容
  20. buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
  21. } catch (Exception e) {
  22. throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e);
  23. }
  24. }

至此,我们已经对xxxMapper.xml文件进行解析,并封装为XMLMapperBuilder对象。然后我们回到MapperAnnotationBuilder类的parse()方法中是如何将XMLMapperBuilder对象转换为MappedStatement对象的,在parse()方法中会调用parseStatement()方法创建MappedStatement对象,源码如下:

  1. void parseStatement(Method method) {
  2. Class<?> parameterTypeClass = getParameterType(method);
  3. LanguageDriver languageDriver = getLanguageDriver(method);
  4. SqlSource sqlSource = getSqlSourceFromAnnotations(method, parameterTypeClass, languageDriver);
  5. if (sqlSource != null) {
  6. Options options = method.getAnnotation(Options.class);
  7. final String mappedStatementId = type.getName() + "." + method.getName();
  8. Integer fetchSize = null;
  9. Integer timeout = null;
  10. StatementType statementType = StatementType.PREPARED;
  11. ResultSetType resultSetType = ResultSetType.FORWARD_ONLY;
  12. SqlCommandType sqlCommandType = getSqlCommandType(method);
  13. boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
  14. boolean flushCache = !isSelect;
  15. boolean useCache = isSelect;
  16. KeyGenerator keyGenerator;
  17. String keyProperty = "id";
  18. String keyColumn = null;
  19. if (SqlCommandType.INSERT.equals(sqlCommandType) || SqlCommandType.UPDATE.equals(sqlCommandType)) {
  20. // first check for SelectKey annotation - that overrides everything else
  21. SelectKey selectKey = method.getAnnotation(SelectKey.class);
  22. if (selectKey != null) {
  23. keyGenerator = handleSelectKeyAnnotation(selectKey, mappedStatementId, getParameterType(method), languageDriver);
  24. keyProperty = selectKey.keyProperty();
  25. } else if (options == null) {
  26. keyGenerator = configuration.isUseGeneratedKeys() ? new Jdbc3KeyGenerator() : new NoKeyGenerator();
  27. } else {
  28. keyGenerator = options.useGeneratedKeys() ? new Jdbc3KeyGenerator() : new NoKeyGenerator();
  29. keyProperty = options.keyProperty();
  30. keyColumn = options.keyColumn();
  31. }
  32. } else {
  33. keyGenerator = new NoKeyGenerator();
  34. }
  35. if (options != null) {
  36. if (FlushCachePolicy.TRUE.equals(options.flushCache())) {
  37. flushCache = true;
  38. } else if (FlushCachePolicy.FALSE.equals(options.flushCache())) {
  39. flushCache = false;
  40. }
  41. useCache = options.useCache();
  42. fetchSize = options.fetchSize() > -1 || options.fetchSize() == Integer.MIN_VALUE ? options.fetchSize() : null; //issue #348
  43. timeout = options.timeout() > -1 ? options.timeout() : null;
  44. statementType = options.statementType();
  45. resultSetType = options.resultSetType();
  46. }
  47. String resultMapId = null;
  48. ResultMap resultMapAnnotation = method.getAnnotation(ResultMap.class);
  49. if (resultMapAnnotation != null) {
  50. String[] resultMaps = resultMapAnnotation.value();
  51. StringBuilder sb = new StringBuilder();
  52. for (String resultMap : resultMaps) {
  53. if (sb.length() > 0) {
  54. sb.append(",");
  55. }
  56. sb.append(resultMap);
  57. }
  58. resultMapId = sb.toString();
  59. } else if (isSelect) {
  60. resultMapId = parseResultMap(method);
  61. }
  62. assistant.addMappedStatement(
  63. mappedStatementId,
  64. sqlSource,
  65. statementType,
  66. sqlCommandType,
  67. fetchSize,
  68. timeout,
  69. // ParameterMapID
  70. null,
  71. parameterTypeClass,
  72. resultMapId,
  73. getReturnType(method),
  74. resultSetType,
  75. flushCache,
  76. useCache,
  77. // TODO gcode issue #577
  78. false,
  79. keyGenerator,
  80. keyProperty,
  81. keyColumn,
  82. // DatabaseID
  83. null,
  84. languageDriver,
  85. // ResultSets
  86. options != null ? nullOrEmpty(options.resultSets()) : null);
  87. }
  88. }

调用MapperBuilderAssistant对象的addMappedStatement方法创建了MappedStatement对象,源码如下:

  1. public MappedStatement addMappedStatement(
  2. String id,
  3. SqlSource sqlSource,
  4. StatementType statementType,
  5. SqlCommandType sqlCommandType,
  6. Integer fetchSize,
  7. Integer timeout,
  8. String parameterMap,
  9. Class<?> parameterType,
  10. String resultMap,
  11. Class<?> resultType,
  12. ResultSetType resultSetType,
  13. boolean flushCache,
  14. boolean useCache,
  15. boolean resultOrdered,
  16. KeyGenerator keyGenerator,
  17. String keyProperty,
  18. String keyColumn,
  19. String databaseId,
  20. LanguageDriver lang,
  21. String resultSets) {
  22. if (unresolvedCacheRef) {
  23. throw new IncompleteElementException("Cache-ref not yet resolved");
  24. }
  25. id = applyCurrentNamespace(id, false);
  26. boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
  27. MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, id, sqlSource, sqlCommandType)
  28. .resource(resource)
  29. .fetchSize(fetchSize)
  30. .timeout(timeout)
  31. .statementType(statementType)
  32. .keyGenerator(keyGenerator)
  33. .keyProperty(keyProperty)
  34. .keyColumn(keyColumn)
  35. .databaseId(databaseId)
  36. .lang(lang)
  37. .resultOrdered(resultOrdered)
  38. .resultSets(resultSets)
  39. .resultMaps(getStatementResultMaps(resultMap, resultType, id))
  40. .resultSetType(resultSetType)
  41. .flushCacheRequired(valueOrDefault(flushCache, !isSelect))
  42. .useCache(valueOrDefault(useCache, isSelect))
  43. .cache(currentCache);
  44. ParameterMap statementParameterMap = getStatementParameterMap(parameterMap, parameterType, id);
  45. if (statementParameterMap != null) {
  46. statementBuilder.parameterMap(statementParameterMap);
  47. }
  48. MappedStatement statement = statementBuilder.build();
  49. // 将MappedStatment对象放到Configuration对象中的map集合中
  50. configuration.addMappedStatement(statement);
  51. return statement;
  52. }

创建了MappedStatement对象之后,就调用了Configuration的addMappedStatement方法,从而添加到了Configuration中的mappedStatements集合中,而key就是MappedStatement的id

总结:
MapperRegistry就是Mapper的注册中心,有两个属性一个是全局配置Configuration还有一个是已经加载过的mapper集合 knownMappers
新增一个mapper的方法就是addMapper,就是向knownsMappers集合中put一条新的mapper记录,key就是mapper的类名全称,value是这个mapper的代理工厂;
分析到这里,发现Configuration对象初始化的时候会解析所有的xml文件中配置的所有mapper接口,并添加到Configuration的mapper集合knowMappers中,但是貌似还没有MappedStatement的影子,也没有看到哪里解析了mapper.xml配置。
不用急,上面源码的第52行就是了,52到54行的意思目前还没有看源码,但是先猜测下:52行是通过Configuration对象和mapper类来构造一个MapperAnnotationBuilder对象,通过字面意思是Mapper的构建类,而第53行的parse(),应该就是解析mapper.xml文件的,第54行标记加载完成,
只有当mapper接口和mapper.xml匹配成功才能叫做是加载成功,所以下一章篇就再来看看MappedStatement是如何创建的。
总结:MappedStatement类就是对应的Mapper.xml中的一个sql语句

9. 执行Mapper接口

我们已经知道MyBatis是如何加载Mapper接口和Mapper.xml对应的sql语句到Configuration对象的,这里我们分析Mapper接口是如何执行的

首先还是SqlSession接口的一个方法说起,也就是

  1. T getMapper(Class type);

很显然这个方法是更加Class名获取该类的一个实例,而Mapper接口只定义了接口没有实现类,那么猜想可知返回的应该就是更加mapper.xml生成的实例了。分析默认实现类DefaultSqlSession类

  1. @Override
  2. public <T> T getMapper(Class<T> type) {
  3. return configuration.<T>getMapper(type, this);
  4. }

方法很简单,调用了Configuration对象的getMapper方法,那么接下来再看下Configuration里面是如何实现的。代码如下:

  1. public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
  2. return mapperRegistry.getMapper(type, sqlSession);
  3. }

调用了mapperRegistry的getMapper方法,参数分别是Class对象和sqlSession,再继续看MapperRegistry的实现,代码如下:

  1. @SuppressWarnings("unchecked")
  2. public <T> T getMapper(Class<T> type, SqlSession sqlSession)
  3. {
  4. // 从konwMappers获取MapperProxyFactory对象
  5. final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>)knownMappers.get(type);
  6. if (mapperProxyFactory == null)
  7. {
  8. throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
  9. }
  10. try
  11. {
  12. // 通过mapper代理工厂创建新实例
  13. return mapperProxyFactory.newInstance(sqlSession);
  14. }
  15. catch (Exception e)
  16. {
  17. throw new BindingException("Error getting mapper instance. Cause: " + e, e);
  18. }
  19. }

可以看出是根据type从knowMappers集合中获取该mapper的代理工厂类,如何通过该代理工厂新建一个实例。再看下代理工厂是如何创建实例的,代码如下:

  1. @SuppressWarnings("unchecked")
  2. protected T newInstance(MapperProxy<T> mapperProxy) {
  3. //通过代理获取mapper接口的新实例
  4. //代理对象的InvocationHandler对象是MapperProxy对象
  5. return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  6. }
  7. public T newInstance(SqlSession sqlSession) {
  8. //创建mapper代理对象,调用newInstance方法
  9. // MapperProxy是一个InvocationHandler
  10. final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
  11. return newInstance(mapperProxy);
  12. }

那么现在我们就知道是如何根据Mapper.class来获取Mapper接口的实例的了,不过,到目前为止貌似还是没有看到和MappedStatement产生联系,别急,再往下看通过代理产生的mapper实例执行具体的方法是如何进行的。代理对象首先会执行InvocationHandler的invoke()方法,也就是MapperProxy类的invoke()方法,代码如下:

  1. @Override
  2. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  3. //判断执行的方法是否是来自父类Object类的方法,也就是如toString、hashCode等方法
  4. //如果是则直接通过反射执行该方法,如果不是Object的方法则再往下走,如果不加这个判断会发生什么呢?
  5. //由于mapper接口除了定义的接口方法还包括继承于Object的方法,如果不加判断则会继续往下走,而下面的执行过程是从mapper.xml寻找对应的实现方法,
  6. //由于mapper.xml只实现了mapper中的接口方法,而没有toString和hashCode方法,从而就会导致这些方法无法被实现。
  7. if (Object.class.equals(method.getDeclaringClass())) {
  8. try {
  9. return method.invoke(this, args);
  10. } catch (Throwable t) {
  11. throw ExceptionUtil.unwrapThrowable(t);
  12. }
  13. }
  14. final MapperMethod mapperMethod = cachedMapperMethod(method);
  15. //执行mapperMethod对象的execute方法
  16. return mapperMethod.execute(sqlSession, args);
  17. }
  18. private MapperMethod cachedMapperMethod(Method method) {
  19. //从缓存中根据method对象获取MapperMethod对象
  20. MapperMethod mapperMethod = methodCache.get(method);
  21. if (mapperMethod == null) {
  22. //如果mapperMethod为空则新建MapperMethod方法
  23. mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
  24. methodCache.put(method, mapperMethod);
  25. }
  26. return mapperMethod;
  27. }

可以看出代理执行mapper接口的方法会先创建一个MapperMethod对象,然后执行execute方法,代码如下:

  1. public Object execute(SqlSession sqlSession, Object[] args) {
  2. Object result;
  3. if (SqlCommandType.INSERT == command.getType()) {//如果执行insert命令
  4. Object param = method.convertArgsToSqlCommandParam(args);//构建参数
  5. result = rowCountResult(sqlSession.insert(command.getName(), param));//调用sqlSession的insert方法
  6. } else if (SqlCommandType.UPDATE == command.getType()) {//如果执行update命令
  7. Object param = method.convertArgsToSqlCommandParam(args);//构建参数
  8. result = rowCountResult(sqlSession.update(command.getName(), param));//调用sqlSession的update方法
  9. } else if (SqlCommandType.DELETE == command.getType()) {//如果执行delete命令
  10. Object param = method.convertArgsToSqlCommandParam(args);//构建参数
  11. result = rowCountResult(sqlSession.delete(command.getName(), param));//调用sqlSession的delete方法
  12. } else if (SqlCommandType.SELECT == command.getType()) {//如果执行select命令
  13. if (method.returnsVoid() && method.hasResultHandler()) {//判断接口返回类型,更加返回数据类型执行对应的select语句
  14. executeWithResultHandler(sqlSession, args);
  15. result = null;
  16. } else if (method.returnsMany()) {
  17. result = executeForMany(sqlSession, args);
  18. } else if (method.returnsMap()) {
  19. result = executeForMap(sqlSession, args);
  20. } else if (method.returnsCursor()) {
  21. result = executeForCursor(sqlSession, args);
  22. } else {
  23. Object param = method.convertArgsToSqlCommandParam(args);
  24. result = sqlSession.selectOne(command.getName(), param);
  25. }
  26. } else if (SqlCommandType.FLUSH == command.getType()) {
  27. result = sqlSession.flushStatements();
  28. } else {
  29. throw new BindingException("Unknown execution method for: " + command.getName());
  30. }
  31. if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
  32. throw new BindingException("Mapper method '" + command.getName()
  33. + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
  34. }
  35. return result;
  36. }

可以看出大致的执行过程就是更加MapperMethod的方法类型,然后构建对应的参数,然后执行sqlSession的方法。到现在还是没有MappedStatement的影子,再看看MapperMethod是被创建的。

  1. private final SqlCommand command;
  2. private final MethodSignature method;
  3. public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
  4. this.command = new SqlCommand(config, mapperInterface, method);
  5. this.method = new MethodSignature(config, mapperInterface, method);
  6. }

这里涉及到了两个类SqlCommand和MethodSignature,先从SqlCommand看起。

  1. public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
  2. String statementName = mapperInterface.getName() + "." + method.getName();//接口方法名
  3. MappedStatement ms = null;
  4. if (configuration.hasStatement(statementName)) {
  5. //从configuration中根据接口名获取MappedStatement对象
  6. ms = configuration.getMappedStatement(statementName);
  7. } else if (!mapperInterface.equals(method.getDeclaringClass())) { // issue #35
  8. //如果该方法不是该mapper接口的方法,则从mapper的父类中找寻该接口对应的MappedStatement对象
  9. String parentStatementName = method.getDeclaringClass().getName() + "." + method.getName();
  10. if (configuration.hasStatement(parentStatementName)) {
  11. ms = configuration.getMappedStatement(parentStatementName);
  12. }
  13. }
  14. if (ms == null) {
  15. if(method.getAnnotation(Flush.class) != null){
  16. name = null;
  17. type = SqlCommandType.FLUSH;
  18. } else {
  19. throw new BindingException("Invalid bound statement (not found): " + statementName);
  20. }
  21. } else {
  22. name = ms.getId();//设置name为MappedStatement的id,而id的值就是xml中对应的sql语句
  23. type = ms.getSqlCommandType();//设置type为MappedStatement的sql类型
  24. if (type == SqlCommandType.UNKNOWN) {
  25. throw new BindingException("Unknown execution method for: " + name);
  26. }
  27. }
  28. }

到这里终于是看到了MappedStatement的身影,根据mapper的Class对象和method对象从Configuration对象中获取指定的MappedStatement对象,然后根据MappedStatement对象的值初始化SqlCommand对象的属性。而MethodSignature则是sql语句的签名,主要作用就是对sql参数与返回结果类型的判断。
总结:
1、sqlSession调用configuration对象的getMapper方法,configuration调用mapperRegistry的getMapper方法
2、mapperRegistry根据mapper获取对应的Mapper代理工厂
3、通过mapper代理工厂创建mapper的代理
4、执行mapper方法时,通过代理调用,创建该mapper方法的MapperMethod对象
5、MapperMethod对象的创建是通过从configuration对象中获取指定的MappedStatement对象来获取具体的sql语句以及参数和返回结果类型
6、调用sqlSession对应的insert、update、delete和select方法执行mapper的方法

10. 执行器Executor解析

我们知道了sql的具体执行是通过调用SqlSession接口的对应的方法去执行的,而SqlSession最终都是通过调用了自己的Executor对象的query和update去执行的。本文就分析下sql的执行器——-Executor
Executor是mybatis的sql执行器,SqlSession是面向程序的,而Executor则就是面向数据库的,先看下Executor接口的方法有哪些,源码如下:

  1. public interface Executor {
  2. ResultHandler NO_RESULT_HANDLER = null;
  3. int update(MappedStatement ms, Object parameter) throws SQLException;
  4. <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey cacheKey, BoundSql boundSql) throws SQLException;
  5. <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException;
  6. <E> Cursor<E> queryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds) throws SQLException;
  7. List<BatchResult> flushStatements() throws SQLException;
  8. void commit(boolean required) throws SQLException;
  9. void rollback(boolean required) throws SQLException;
  10. CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql);
  11. boolean isCached(MappedStatement ms, CacheKey key);
  12. void clearLocalCache();
  13. void deferLoad(MappedStatement ms, MetaObject resultObject, String property, CacheKey key, Class<?> targetType);
  14. Transaction getTransaction();
  15. void close(boolean forceRollback);
  16. boolean isClosed();
  17. void setExecutorWrapper(Executor executor);
  18. }

和SqlSession一样定义了各种各样的sql执行的方法,有查询的query方法,有更新的update方法,以及和事务有关的commit方法和rollback方法等,接下来就以query方法为例,看下具体是如何执行的。
Executor接口共有两个实现类,分别是BaseExecutor和CachingExecutor,CachingExecutor是缓存执行器,后面会提到,现在先看下BaseExecutor
BaseExecutor的属性有:

  1. private static final Log log = LogFactory.getLog(BaseExecutor.class);
  2. //事务
  3. protected Transaction transaction;
  4. //执行器包装者
  5. protected Executor wrapper;
  6. //线程安全队列
  7. protected ConcurrentLinkedQueue<DeferredLoad> deferredLoads;
  8. //本地缓存
  9. protected PerpetualCache localCache;
  10. protected PerpetualCache localOutputParameterCache;
  11. protected Configuration configuration;
  12. //查询次数栈
  13. protected int queryStack;
  14. //是否已关闭(回滚的时候会被关闭)
  15. private boolean closed;

再看下BaseExecutor执行query方法的源码:

  1. public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
  2. ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
  3. if (closed) {//判断执行器是否已关闭
  4. throw new ExecutorException("Executor was closed.");
  5. }
  6. //如果查询次数栈为0并且MappedStatement可以清除缓存,则清除本地缓存
  7. if (queryStack == 0 && ms.isFlushCacheRequired()) {
  8. clearLocalCache();
  9. }
  10. List<E> list;
  11. try {
  12. queryStack++;//查询次数+1
  13. list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;//从缓存中根据缓存key查询是否有缓存
  14. if (list != null) {
  15. //如果缓存中有数据,则处理缓存
  16. handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
  17. } else {
  18. //如果缓存中没有数据,则从数据库查询数据
  19. list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
  20. }
  21. } finally {
  22. //查询次数-1
  23. queryStack--;
  24. }
  25. if (queryStack == 0) {
  26. for (DeferredLoad deferredLoad : deferredLoads) {
  27. deferredLoad.load();
  28. }
  29. // issue #601
  30. deferredLoads.clear();
  31. if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
  32. // issue #482
  33. clearLocalCache();
  34. }
  35. }
  36. return list;
  37. }

可以看出BaseExecutor会优先从缓存中查询数据,如果缓存不为空再从数据库数据。在这里有一个queryStack会进行自增自减,它的作用是什么呢?先看下如果没有缓存的话,BaseExecutor是怎么从数据库查询数据的:

  1. private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
  2. List<E> list;
  3. localCache.putObject(key, EXECUTION_PLACEHOLDER);
  4. try {
  5. list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);//执行doQuery方法
  6. } finally {
  7. localCache.removeObject(key);
  8. }
  9. localCache.putObject(key, list);//将查询结果放入缓存
  10. if (ms.getStatementType() == StatementType.CALLABLE) {//如果callable类型查询
  11. localOutputParameterCache.putObject(key, parameter);//将参数放入缓存中
  12. }
  13. return list;
  14. }

可见该方法是调用了doQuery方法从数据库查询了数据,然后将查询的结果及查询用的参数放入了缓存中,而doQuery方法是BaseExecutor中的抽象方法,具体的实现是由BaseExecutor的子类进行实现

  1. protected abstract int doUpdate(MappedStatement ms, Object parameter)
  2. throws SQLException;
  3. protected abstract List<BatchResult> doFlushStatements(boolean isRollback)
  4. throws SQLException;
  5. protected abstract <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql)
  6. throws SQLException;
  7. protected abstract <E> Cursor<E> doQueryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds, BoundSql boundSql)
  8. throws SQLException;
  9. protected void closeStatement(Statement statement) {
  10. if (statement != null) {
  11. try {
  12. statement.close();
  13. } catch (SQLException e) {
  14. // ignore
  15. }
  16. }
  17. }

BaseExecutor共有SimpleExecutor、ReuseExecutor、BatchExecutor以及ClosedExecutor四个子类,这个后面再分析,现在我们以及知道了SqlSession是调用了Executor的方法来执行sql,而Executor的默认实现类的BaseExecutor,而BaseExecutor又是调用了其子类的方法。而BaseExecutor则对查询的结果进行了缓存处理以及查询的时候会从缓存中进行查询。

11. 总结

  1. 读取mybatis.xml配置文件到Reader或者InputStream流对象中
  2. 在SqlSessionFactoryBuilder中通过build方法中创建XmlConfigBuilder 对象解析流生成Configuration对象,Configuration对象中包括读取Mapper接口(接口代理工厂对象)、读取每个接口对应的每条Sql封装成MapperStatment对象等,都放在Configuration对象中
  3. 在SqlSessionFactoryBuilder中的build方法中,通过Configuration对象创建SqlSessionFactory对象
  4. 通过SqlSessionFactory对象的openSession方法创建SqlSession对象
  5. 在SqlSession对象中调用getMapper方法获取接口代理工厂对象
  6. 执行代理接口方法时,接口代理对象中的invok方法会调用MethodProxy对象的invoke方法,MethodProxy是一个InvocationHandler对象。这个方法会创建一个MapperMethod对象,MapperMethod构造函数会根据执行接口名+方法名找出对应的MapperStatment,execute方法会根据Sql类型调用sqlSession的不同insert、update、delete、select方法。
  7. SqlSession对象最终会将方法执行转交给xecutor对象执行