前言

  mybatis是目前进行java开发 dao层较为流行的框架,其较为轻量级的特性,避免了类似hibernate的重量级封装。同时将sql的查询与与实现分离,实现了sql的解耦。学习成本较hibernate也要少很多。

我们可以先简单的回顾下mybatis的使用方式。一般两种方式,单独使用或者配合spring使用。当然了 我们一般都是使用Spring集成的方式 。下面简要写明下两种的关键步骤

  单独使用

    这儿我们采用手动添加xml配置文件的形式,先加载mybatis配置文件,这儿简要列一下配置文件以及说明

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6.  
  7. <!--用来进行属性配置-->
  8. <properties>
  9. <property name="driver" value="com.mysql.jdbc.Driver"/>
  10. <property name="url" value="jdbc:mysql://192.168.0.1:3306/test"/>
  11. <property name="username" value="root"/>
  12. <property name="password" value="mysql"/>
  13. <!--如果为true 则可以有默认配置 例如下面的password-->
  14. <property name="org.apache.ibatis.parsing.PropertyParser.enable-default-value" value="true"/>
  15. </properties>
  16.  
  17. <!--这是非常重要的设置 会改变mybatis的行为-->
  18. <settings>
  19. <!--全局地开启或关闭配置文件中的所有映射器已经配置的任何缓存。 默认为true-->
  20. <setting name="cacheEnabled" value="true"></setting>
  21. <!-- 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。
  22. 特定关联关系中可通过设置fetchType属性来覆盖该项的开关状态 类似于hibernate的懒加载 默认false-->
  23. <setting name="lazyLoadingEnabled" value="false"></setting>
  24. <!--当开启时,任何方法的调用都会加载该对象的所有属性。否则,每个属性会按需加载 默认false 但是<=3.4.1为true-->
  25. <setting name="aggressiveLazyLoading" value="false"></setting>
  26. <!-- 是否允许单一语句返回多结果集(需要兼容驱动)。 默认为true 目前测试都不起作用-->
  27. <setting name="multipleResultSetsEnabled" value="true"></setting>
  28. <!--使用列标签代替列名。不同的驱动在这方面会有不同的表现, 具体可参考相关驱动文档或通过测试
  29. 这两种不同的模式来观察所用驱动的结果。 默认为true 为false则不能使用别名-->
  30. <setting name="useColumnLabel" value="true"></setting>
  31. <!-- 在执行添加记录之后可以获取到数据库自动生成的主键ID。(如果支持自动生成 如自增) 默认为false-->
  32. <setting name="useGeneratedKeys" value="true"></setting>
  33.  
  34. <!--指定 MyBatis 应如何自动映射列到字段或属性。 NONE 表示取消自动映射;PARTIAL 只会自动映射
  35. 没有定义嵌套结果集映射的结果集。 FULL 会自动映射任意复杂的结果集(无论是否嵌套)。-->
  36. <setting name="autoMappingBehavior" value="PARTIAL"></setting>
  37.  
  38. <!--指定发现自动映射目标未知列(或者未知属性类型)的行为。即查询的数据在返回值有没映射上的结果
  39. NONE: 不做任何反应
  40. WARNING: 输出提醒日志 ('org.apache.ibatis.session.AutoMappingUnknownColumnBehavior' 的日志等级必须设置为 WARN)
  41. FAILING: 映射失败 (抛出 SqlSessionException)-->
  42. <setting name="autoMappingUnknownColumnBehavior" value="NONE"></setting>
  43. <!--配置默认的执行器。SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(prepared statements); BATCH 执行器将重用语句并执行批量更新。-->
  44. <setting name="defaultExecutorType" value="SIMPLE"></setting>
  45. <!--等待数据库响应的时间-->
  46. <setting name="defaultStatementTimeout" value="5000"></setting>
  47. <!--获取的连接数-->
  48. <setting name="defaultFetchSize" value="5"></setting>
  49. <!--允许在嵌套语句中使用分页(RowBounds)。如果允许使用则设置为false-->
  50. <setting name="safeRowBoundsEnabled" value="false"></setting>
  51. <!--允许在嵌套语句中使用分页(ResultHandler)。如果允许使用则设置为false。-->
  52. <setting name="safeResultHandlerEnabled" value="true"></setting>
  53. <!--是否自动开启驼峰命名与bean映射 默认为false-->
  54. <setting name="mapUnderscoreToCamelCase" value="true"></setting>
  55. <!--MyBatis 利用本地缓存机制(Local Cache)防止循环引用(circular references)和加速重复嵌套查询。
  56. 默认值为 SESSION,这种情况下会缓存一个会话中执行的所有查询。 即使一级缓存 局部缓存
  57. 若设置值为 STATEMENT,本地会话仅用在语句执行上,对相同 SqlSession 的不同调用将不会共享数据。-->
  58. <setting name="localCacheScope" value="SESSION"></setting>
  59. <!--当没有为参数提供特定的 JDBC 类型时,为空值指定 JDBC 类型。 某些驱动需要指定列的 JDBC 类型,
  60. 多数情况直接用一般类型即可,比如 NULL、VARCHAR 或 OTHER。-->
  61. <setting name="jdbcTypeForNull" value="OTHER"></setting>
  62. <!--懒加载的方法-->
  63. <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"></setting>
  64. <!--指定动态 SQL 生成的默认语言。 目前系统只有xml 默认即为下面的配置-->
  65. <setting name="defaultScriptingLanguage" value="org.apache.ibatis.scripting.xmltags.XMLLanguageDriver"></setting>
  66. <!--即默认的类型处理器 可以处理pojo类中的枚举类型 插入以及查询 也可以在xml中使用typeHandler
  67. EnumOrdinalTypeHandler即不会使用自己定义的code EnumTypeHandler会使用自定义的code-->
  68. <setting name="defaultEnumTypeHandler" value="org.apache.ibatis.type.EnumTypeHandler"></setting>
  69. <!--为空时需不需要调用set为null的方法 这个map则为put方法 注意map的话为空则不会有为null值的key 所以最好为true 默认false-->
  70. <setting name="callSettersOnNulls" value="true"></setting>
  71. <!--即如果所有的列都为空会返回null 如果为true 则会新建空实例返回 -->
  72. <setting name="returnInstanceForEmptyRow" value="false"></setting>
  73. <!--mybatis 日志前缀 这儿只有查询有关的日志-->
  74. <setting name="logPrefix" value="megalith-hamizz: "></setting>
  75. <!--指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING -->
  76. <setting name="logImpl" value="SLF4J"></setting>
  77. <!--mybatis创建具有延迟加载能力的工具 CGLIB | JAVASSIST 默认后者-->
  78. <setting name="proxyFactory" value="JAVASSIST"></setting>
  79. <!--自定义的虚拟文件系统-->
  80. <!--<setting name="vfsImpl" value=""></setting>-->
  81. <!--貌似这儿如果为true 那么在不能在参数不加注解,直接使用#{0} 或者#{param1} 这种,如果为false则可以 3.4.1开始-->
  82. <setting name="useActualParamName" value="true"></setting>
  83. <!--指定一个提供Configuration实例的类。 这个被返回的Configuration实例用来加载被反序列化对象的懒加载属性值。
  84. 这个类必须包含一个签名方法static Configuration getConfiguration(). (从 3.2.3 版本开始)-->
  85. <!--<setting name="configurationFactory" value=""></setting>-->
  86. </settings>
  87.  
  88. <!--entity 别名 在使用type或者resultType可以直接用这个-->
  89. <typeAliases>
  90. <!--这个是只扫描某个包-->
  91. <!--<package name="com.code.analysis.mybatis.entity" ></package>-->
  92. <!--可以直接在bean上添加 @Alias-->
  93. <typeAlias type="com.code.analysis.mybatis.entity.Test" alias="Test"></typeAlias>
  94. <!--还有内置的一些别名 如map等-->
  95. </typeAliases>
  96.  
  97. <!--类型处理器 注意如果查询用这个 则必须使用resultMap-->
  98. <typeHandlers>
  99. <!--<typeHandler handler=""></typeHandler>-->
  100. </typeHandlers>
  101.  
  102. <!--即mybatis-->
  103. <objectFactory type="com.code.analysis.mybatis.config.MyObjectFactory">
  104. <property name="dilg" value="100"/>
  105. </objectFactory>
  106. <!--插件配置-->
  107. <plugins>
  108. <plugin interceptor="com.code.analysis.mybatis.plugin.ExecutorPlugin"></plugin>
  109. </plugins>
  110.  
  111. <!--环境选择 可以配置多个环境 在构建sqlSessionFacotry的时候可以选择-->
  112. <environments default="development">
  113. <environment id="development">
  114. <transactionManager type="JDBC"/>
  115. <dataSource type="com.code.analysis.mybatis.config.DuidDataSource">
  116. <property name="driver" value="com.mysql.jdbc.Driver"/>
  117. <property name="url" value="jdbc:mysql://127.0.0.1:3306/tjfx"/>
  118. <property name="username" value="root"/>
  119. <property name="password" value="mysql"/>
  120. </dataSource>
  121. </environment>
  122.  
  123. <environment id="prod">
  124. <!--如果使用了spring集成 那么spring会覆盖掉这儿的事物-->
  125. <transactionManager type="JDBC"/>
  126. <dataSource type="POOLED">
  127. <property name="driver" value="${driver}"/>
  128. <property name="url" value="${url}"/>
  129. <property name="username" value="${username}"/>
  130. <property name="password" value="${password:123456}"/>
  131. </dataSource>
  132. </environment>
  133. </environments>
  134.  
  135. <!--sql.xml文件扫描-->
  136. <mappers>
  137. <mapper resource="mappers/UserInfoMapper.xml"/>
  138. </mappers>
  139.  
  140. </configuration>

  然后新建MybatisConfig类,使用静态代码块读取mybatisCofig.xml文件的流,并根据这个流构建SqlSessionFactory

  1. /**
  2. * @Description:
  3. * @author: zhoum
  4. * @Date: 2019-02-14
  5. * @Time: 15:38
  6. */
  7. public class MybatisConfig {
  8.  
  9. private static SqlSessionFactory sqlSessionFactory;
  10.  
  11. static {
  12. try {
  13. InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
  14. //这儿主要可以传入的参数有configuration 或者配置文件流 或者环境 或者配置属性 很灵活
  15. sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream,"development");
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. }
  19. }
  20.  
  21. public static SqlSession getSession(){
  22.  
  23. return sqlSessionFactory.openSession();
  24. }
  25. }

  使用方式,假设已经建立了数据库,并且建立了名为user_info的表,系统也建立了对应的mapper.xml  且已经写了对应的sql ,mapper接口 且已经写了对应的方法,则可以按如下方式使用mybatis

  1. public class MainTest {
  2.  
  3. public static Logger logger = LoggerFactory.getLogger(MainTest.class);
  4. public static void main(String[] args) throws IOException {
  5.  
  6. SqlSession session = MybatisConfig.getSession();
  7. UserInfoMapper mapper = session.getMapper(UserInfoMapper.class);
  8. UserInfo user = mapper.seleceCase();
  9. System.out.println(user);
  10. logger.info("查询成功");
  11. session.close();
  12. }
  13. }

  到这儿我们就成功的使用了mybatis,根据这个main方式我们就可以得知,我们是根据SqlSessionFactory打开一个SqlSession  根据这个SqlSession拿到对应的接口,然后执行方法即可执行对应mapper.xml中的sql命令 并封装数据返回。核心有两个地方,1是构造SqlSessionFactory,2是根据SqlSession获得mapper。 关于2我们后面的文章再详细分析。本文先主要讲如何构造一个SqlSessionFactory,根据上面的源码我们接着看

  1. public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
  2. try {
  3. //根据传入的参数获取对应的XMLConfigBilder
  4. XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
  5. //执行构造方法 构造一个DefaultSqlSessionFactory
  6. return build(parser.parse());
  7. } catch (Exception e) {
  8. throw ExceptionFactory.wrapException("Error building SqlSession.", e);
  9. } finally {
  10. ErrorContext.instance().reset();
  11. try {
  12. inputStream.close();
  13. } catch (IOException e) {
  14. // Intentionally ignore. Prefer previous error.
  15. }
  16. }
  17. }
  18.  
  19. public SqlSessionFactory build(Configuration config) {
  20. return new DefaultSqlSessionFactory(config);
  21. }

  上面的代码可以得知,程序根据我们的配置文件流创建了一个XmlConfigBuilder对象,并执行对应的parse()方法生成一个Configuration对象,然后使用这个config创建了一个默认的DefaultSqlSessionFactory。核心又有两个地方  生成创建XmlConfigBuilder  以及他的parse()方法,这两个方法因为在使用Spring集成的时候也会用上,所以这里不讲,下面集成Spring时到这儿了则一块讲,使用Spring集成的方式也是我们标准的用法,下面简单说下Spring集成的方式。

  Spring集成

这儿使用springboot的方式,可以简化下其他配置。这儿主要说明一些核心步骤,

  需要几个核心依赖包

  1. //添加jdbc
  2. compile group: 'org.springframework.boot', name: 'spring-boot-starter-jdbc', version: '2.0.3.RELEASE'
  3. //添加mysql驱动
  4. compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.18'
  5. compile group: 'com.alibaba', name: 'druid', version: '1.1.21'
  6. //添加mybatis
  7. compile group: 'org.mybatis', name: 'mybatis', version: '3.5.3'
  8. compile group: 'org.mybatis', name: 'mybatis-spring', version: '2.0.3'

 springboot配置文件

  1. spring:
  2. application:
  3. name: bootjar
  4. datasource:
  5. username: root
  6. password: 123456
  7. url: jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
  8. driver-class-name: com.mysql.jdbc.Driver
  9. type: com.alibaba.druid.pool.DruidDataSource
  10. logging:
  11. level:
  12. root: info

mybatis的配置类 由于一些配置功能在上面的config文件中已经说明了,所以这儿就比较的简化配置

  1. @Configuration
  2. public class MybatisConfig {
  3.  
  4. @Bean
  5. @Autowired
  6. public SqlSessionFactoryBean initMybatis(DataSource dataSource) throws IOException {
  7. org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
  8. SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
  9. //设置配置
  10. sqlSessionFactoryBean.setConfiguration(configuration);
  11. //设置数据源 这个数据源是spring加载的
  12. sqlSessionFactoryBean.setDataSource(dataSource);
  13. //扫描xml路径
  14. sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/mapper/**.xml"));
  15. return sqlSessionFactoryBean;
  16. }
  17.  
  18. }

  使用的方式依然如下,当然spring有默认可以注入mapper接口的方式,不过本文主要探究SqlSessionFactory加载原理,所以暂时不讲

  1. @Autowired
  2. private SqlSessionFactory sqlSessionFactory;
  3.  
  4. public UserInfo getUser(){
  5. SqlSession sqlSession = sqlSessionFactory.openSession();
  6. UserInfoMapper mapper = sqlSession.getMapper(UserInfoMapper.class);
  7. UserInfo userInfo = mapper.selectInfo();
  8. sqlSession.close();
  9. return userInfo;
  10. }

  上面就是普通使用,和spring集成的方式。接下来我主要通过Spring集成的案例来讲解

正文

1.加载mapper文件数据

  mapper文件即我们编写sql语句的地方,也是mybatis解耦合的设计标志

  我们在spring配置mybatis的方法中可以看到这行代码

  1. sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/mapper/**.xml"));

  而设置的mypperLocation点进源码查看,可以得知通过 new PathMatchingResourcePatternResolver().getResources("classpath*:/mapper/**.xml")方法获取到了我们系统中所有mapper.xml文件的资源,并赋值给了SqlSessionFactoryBean。当然这儿我选用了PathMatchingResourcePatternResolver查找器,也可以使用其他的查找器

  1. private Resource[] mapperLocations;
  2.  
  3. public void setMapperLocations(Resource... mapperLocations) {
  4. this.mapperLocations = mapperLocations;
  5. }

  所以我们可以得知加载mapper.xml的主要方法就在这儿,我们接着往里面看逻辑

  1. String CLASSPATH_ALL_URL_PREFIX = "classpath*:";
  2.  
  3. @Override
  4. public Resource getResource(String location) {
  5. return getResourceLoader().getResource(location);
  6. }
  7.  
  8. @Override
  9. public Resource[] getResources(String locationPattern) throws IOException {
  10. //判断下获取资源的地址不能为空
  11. Assert.notNull(locationPattern, "Location pattern must not be null");
  12. //判断是否是根据类加载路径地址来加载
  13. if (locationPattern.startsWith(CLASSPATH_ALL_URL_PREFIX)) {
  14. // //判断后面的有用地址中是否有通配符
  15. if (getPathMatcher().isPattern(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()))) {
  16. //根据通配符 查找满足通配符的文件资源
  17. return findPathMatchingResources(locationPattern);
  18. }
  19. else {
  20. // 查找下面所有的文件资源
  21. return findAllClassPathResources(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()));
  22. }
  23. }
  24. else {
  25. //解析出有用的地址开头
  26. int prefixEnd = (locationPattern.startsWith("war:") ? locationPattern.indexOf("*/") + 1 :
  27. locationPattern.indexOf(':') + 1);
  28. //判断解析后的地址开头后的地址中是否有 "*"或者 "?" 即是否有通配符
  29. if (getPathMatcher().isPattern(locationPattern.substring(prefixEnd))) {
  30. // 则返回所有满足条件的资源
  31. return findPathMatchingResources(locationPattern);
  32. }
  33. else {
  34. // 查询单个资源
  35. return new Resource[] {getResourceLoader().getResource(locationPattern)};
  36. }
  37. }
  38. }

  可以看到这个方法主要的作用就是加载到传入的指定的location中满足条件的文件,我们传入的是classpath*:/mapper/**.xml,所以这儿会执行findPathMatchingResources方法 并会传入/mapper/**.xml参数,我们接着源码看

  1. protected Resource[] findPathMatchingResources(String locationPattern) throws IOException {
  2. //根据我们传入的地址 解析出顶级文件夹地址 本例即class*:/mapper/ 去掉了后面的匹配规则
  3. String rootDirPath = determineRootDir(locationPattern);
  4. //根据顶级地址截取后面的匹配规则,如本例则为**.xml
  5. String subPattern = locationPattern.substring(rootDirPath.length());
  6. //获取顶级文件夹的转换为Resource 这儿又会回去执行刚才的即上面的findAllClassPathResources(String location)方法
  7. Resource[] rootDirResources = getResources(rootDirPath);
  8.  
  9. Set<Resource> result = new LinkedHashSet<>(16);
  10. //遍历找到的顶级文件夹资源
  11. for (Resource rootDirResource : rootDirResources) {
  12. //这个方法可以自己继承 做一下自定义处理 默认不处理 直接返回
  13. rootDirResource = resolveRootDirResource(rootDirResource);
  14. //获取到文件夹绝对路径
  15. URL rootDirUrl = rootDirResource.getURL();
  16.  
  17. //对特殊的文件夹做的一些额外处理
  18. if (equinoxResolveMethod != null && rootDirUrl.getProtocol().startsWith("bundle")) {
  19. URL resolvedUrl = (URL) ReflectionUtils.invokeMethod(equinoxResolveMethod, null, rootDirUrl);
  20. if (resolvedUrl != null) {
  21. rootDirUrl = resolvedUrl;
  22. }
  23. rootDirResource = new UrlResource(rootDirUrl);
  24. }
  25. //是否是jboss的vfs资源
  26. if (rootDirUrl.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
  27. result.addAll(VfsResourceMatchingDelegate.findMatchingResources(rootDirUrl, subPattern, getPathMatcher()));
  28. }
  29. //是否是jar资源 如果是做处理
  30. else if (ResourceUtils.isJarURL(rootDirUrl) || isJarResource(rootDirResource)) {
  31. result.addAll(doFindPathMatchingJarResources(rootDirResource, rootDirUrl, subPattern));
  32. }
  33. //否则进行普通处理
  34. else {
  35. result.addAll(doFindPathMatchingFileResources(rootDirResource, subPattern));
  36. }
  37. }
  38. if (logger.isDebugEnabled()) {
  39. logger.debug("Resolved location pattern [" + locationPattern + "] to resources " + result);
  40. }
  41. //将找到的结果结果转换为数组返回
  42. return result.toArray(new Resource[0]);
  43. }

  可以看到该方法主要是根据我们传入的location地址,解析到其根文件夹,以及匹配规则,根据这两者来执行doFindPathMatchingFileResources方法获取到满足匹配规则的文件,我们接着往下看

  1. protected Set<Resource> doFindPathMatchingFileResources(Resource rootDirResource, String subPattern)
  2. throws IOException {
  3.  
  4. File rootDir;
  5. try {
  6. //根据resource解析出对应的绝对路径的文件夹
  7. rootDir = rootDirResource.getFile().getAbsoluteFile();
  8. }
  9. catch (IOException ex) {
  10. if (logger.isWarnEnabled()) {
  11. logger.warn("Cannot search for matching files underneath " + rootDirResource +
  12. " because it does not correspond to a directory in the file system", ex);
  13. }
  14. return Collections.emptySet();
  15. }
  16. //继续执行
  17. return doFindMatchingFileSystemResources(rootDir, subPattern);
  18. }
  19.  
  20. protected Set<Resource> doFindMatchingFileSystemResources(File rootDir, String subPattern) throws IOException {
  21. if (logger.isDebugEnabled()) {
  22. logger.debug("Looking for matching resources in directory tree [" + rootDir.getPath() + "]");
  23. }
  24. //获取到所有的满足条件的文件
  25. Set<File> matchingFiles = retrieveMatchingFiles(rootDir, subPattern);
  26. Set<Resource> result = new LinkedHashSet<>(matchingFiles.size());
  27. for (File file : matchingFiles) {
  28. //将所有的文件转换为Resource放入result并返回
  29. result.add(new FileSystemResource(file));
  30. }
  31. return result;
  32. }

  这两步都是做了一些普通的转换,关键在于retrieveMatchingFiles方法获取到的满足条件的文件,我们接着看

  1. protected Set<File> retrieveMatchingFiles(File rootDir, String pattern) throws IOException {
  2. //判断文件是否存在
  3. if (!rootDir.exists()) {
  4. // Silently skip non-existing directories.
  5. if (logger.isDebugEnabled()) {
  6. logger.debug("Skipping [" + rootDir.getAbsolutePath() + "] because it does not exist");
  7. }
  8. return Collections.emptySet();
  9. }
  10. //判断是否是文件夹
  11. if (!rootDir.isDirectory()) {
  12. // Complain louder if it exists but is no directory.
  13. if (logger.isWarnEnabled()) {
  14. logger.warn("Skipping [" + rootDir.getAbsolutePath() + "] because it does not denote a directory");
  15. }
  16. return Collections.emptySet();
  17. }
  18. //判断文件夹是否可读
  19. if (!rootDir.canRead()) {
  20. if (logger.isWarnEnabled()) {
  21. logger.warn("Cannot search for matching files underneath directory [" + rootDir.getAbsolutePath() +
  22. "] because the application is not allowed to read the directory");
  23. }
  24. return Collections.emptySet();
  25. }
  26. //得到完整的文件夹路径 并且将不同机器的分隔符统一为/
  27. String fullPattern = StringUtils.replace(rootDir.getAbsolutePath(), File.separator, "/");
  28. //如果匹配规则前每加/ 则路径后面需要加上 为的是拼凑城一个完整路径的匹配规则 即类似d:/test/mapper/**.xml
  29. if (!pattern.startsWith("/")) {
  30. fullPattern += "/";
  31. }
  32. //拼接完整匹配规则 并且将不同机器的分隔符统一为/
  33. fullPattern = fullPattern + StringUtils.replace(pattern, File.separator, "/");
  34. Set<File> result = new LinkedHashSet<>(8);
  35. //继续执行
  36. doRetrieveMatchingFiles(fullPattern, rootDir, result);
  37. return result;
  38. }

  这个方法主要对路径做了一些适应处理 继续看关键的

  1. protected void doRetrieveMatchingFiles(String fullPattern, File dir, Set<File> result) throws IOException {
  2. if (logger.isDebugEnabled()) {
  3. logger.debug("Searching directory [" + dir.getAbsolutePath() +
  4. "] for files matching pattern [" + fullPattern + "]");
  5. }
  6. //找到文件夹下所有的文件或者文件夹
  7. File[] dirContents = dir.listFiles();
  8. if (dirContents == null) {
  9. if (logger.isWarnEnabled()) {
  10. logger.warn("Could not retrieve contents of directory [" + dir.getAbsolutePath() + "]");
  11. }
  12. return;
  13. }
  14. //排个序
  15. Arrays.sort(dirContents);
  16. //遍历文件
  17. for (File content : dirContents) {
  18. //得到每个文件的绝对路径
  19. String currPath = StringUtils.replace(content.getAbsolutePath(), File.separator, "/");
  20. //如果是文件夹 且文件夹满足通配规则
  21. if (content.isDirectory() && getPathMatcher().matchStart(fullPattern, currPath + "/")) {
  22.  
  23. if (!content.canRead()) {
  24. //如果不可读 那就记录下日志即可
  25. if (logger.isDebugEnabled()) {
  26. logger.debug("Skipping subdirectory [" + dir.getAbsolutePath() +
  27. "] because the application is not allowed to read the directory");
  28. }
  29. }
  30. else {
  31. //并且可读 则传入文件夹 以及通配符规则 set集合递归收集
  32. doRetrieveMatchingFiles(fullPattern, content, result);
  33. }
  34. }
  35. //如果是文件且满足我们的通配符规则 则 添加进去
  36. if (getPathMatcher().match(fullPattern, currPath)) {
  37. result.add(content);
  38. }
  39. }
  40. }

  千呼万唤啊,做了这么多铺垫终于来到了最核心的加载方法了,通过这个方法可以得知,通过我们传入的根目录,遍历下面的文件或者文件夹,如果是文件且名字满足通配符就添加进我们的set,如果是文件夹且满足我们的通配符路径 则继续递归这个方法找到根目录下所有满足条件的文件夹 加入set并返回

  

  好了 至此所有的mapper文件终于是加载到我们的SqlSessionFactoryBean中了 并由 mapperLocations(即Resource[]类型) 进行接收

2.SqlSessionFactorybean.buildSqlSessionFactory()方法

  系统最终会调用我们配置的SqlSessionFactoryBeand.buildSqlSessionFactory()方法类创建需要的SqlSessionFactory  我们的接着看这个方法,这个方法总体如下

  1. protected SqlSessionFactory buildSqlSessionFactory() throws Exception {
  2. //声明config
  3. final Configuration targetConfiguration;
  4. //声明xmlBuilder 解析config
  5. XMLConfigBuilder xmlConfigBuilder = null;
  6. //判断我们是否传入了config
  7. if (this.configuration != null) {
  8. targetConfiguration = this.configuration;
  9. if (targetConfiguration.getVariables() == null) {
  10. targetConfiguration.setVariables(this.configurationProperties);
  11. } else if (this.configurationProperties != null) {
  12. targetConfiguration.getVariables().putAll(this.configurationProperties);
  13. }
  14. }
  15. //如果没传入config 那是否传入了config文件地址
  16. else if (this.configLocation != null) {
  17. //将传入的configLocation resource进行解析
  18. xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
  19. //获得解析后的config
  20. targetConfiguration = xmlConfigBuilder.getConfiguration();
  21. } else {
  22. //都没有的话就直接用系统默认的config
  23. LOGGER.debug(
  24. () -> "Property 'configuration' or 'configLocation' not specified, using default MyBatis Configuration");
  25. targetConfiguration = new Configuration();
  26. Optional.ofNullable(this.configurationProperties).ifPresent(targetConfiguration::setVariables);
  27. }
  28. //如果objectFactory不为空则写入config
  29. Optional.ofNullable(this.objectFactory).ifPresent(targetConfiguration::setObjectFactory);
  30. //如果objectWrapperFactory不为空则写入config
  31. Optional.ofNullable(this.objectWrapperFactory).ifPresent(targetConfiguration::setObjectWrapperFactory);
  32. //如果vfs不为空则写入config
  33. Optional.ofNullable(this.vfs).ifPresent(targetConfiguration::setVfsImpl);
  34.  
  35. //如果别名扫描包地址不为空 则注入别名
  36. if (hasLength(this.typeAliasesPackage)) {
  37. //扫描包下所有类 并去除掉匿名类 非接口的类 成员类 ,将剩下的写入config的alias
  38. scanClasses(this.typeAliasesPackage, this.typeAliasesSuperType).stream()
  39. .filter(clazz -> !clazz.isAnonymousClass()).filter(clazz -> !clazz.isInterface())
  40. .filter(clazz -> !clazz.isMemberClass()).forEach(targetConfiguration.getTypeAliasRegistry()::registerAlias);
  41. }
  42. //如果执行别名不为空 则也写入config
  43. if (!isEmpty(this.typeAliases)) {
  44. Stream.of(this.typeAliases).forEach(typeAlias -> {
  45. targetConfiguration.getTypeAliasRegistry().registerAlias(typeAlias);
  46. LOGGER.debug(() -> "Registered type alias: '" + typeAlias + "'");
  47. });
  48. }
  49.  
  50. //如果拦截器不为空 则将拦截器全部写入config
  51. if (!isEmpty(this.plugins)) {
  52. Stream.of(this.plugins).forEach(plugin -> {
  53. targetConfiguration.addInterceptor(plugin);
  54. LOGGER.debug(() -> "Registered plugin: '" + plugin + "'");
  55. });
  56. }
  57.  
  58. //如果typeHandlersPackage包不为空 即类别转换器 扫描包下所有类 也写入config
  59. if (hasLength(this.typeHandlersPackage)) {
  60. scanClasses(this.typeHandlersPackage, TypeHandler.class).stream().filter(clazz -> !clazz.isAnonymousClass())
  61. .filter(clazz -> !clazz.isInterface()).filter(clazz -> !Modifier.isAbstract(clazz.getModifiers()))
  62. .forEach(targetConfiguration.getTypeHandlerRegistry()::register);
  63. }
  64.  
  65. //如果typeHandlers类不为空 即类别转换器 扫描包下所有类 也写入config
  66. if (!isEmpty(this.typeHandlers)) {
  67. Stream.of(this.typeHandlers).forEach(typeHandler -> {
  68. targetConfiguration.getTypeHandlerRegistry().register(typeHandler);
  69. LOGGER.debug(() -> "Registered type handler: '" + typeHandler + "'");
  70. });
  71. }
  72.  
  73. //如果scriptingLanguageDrivers类不为空 也写入config
  74. if (!isEmpty(this.scriptingLanguageDrivers)) {
  75. Stream.of(this.scriptingLanguageDrivers).forEach(languageDriver -> {
  76. targetConfiguration.getLanguageRegistry().register(languageDriver);
  77. LOGGER.debug(() -> "Registered scripting language driver: '" + languageDriver + "'");
  78. });
  79. }
  80. //默认的scriptingLanguageDrivers不为null的话也写入
  81. Optional.ofNullable(this.defaultScriptingLanguageDriver)
  82. .ifPresent(targetConfiguration::setDefaultScriptingLanguage);
  83.  
  84. //如果指定的数据库id不为空 则写入当前配置支持的数据库id
  85. if (this.databaseIdProvider != null) {// fix #64 set databaseId before parse mapper xmls
  86. try {
  87. targetConfiguration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource));
  88. } catch (SQLException e) {
  89. throw new NestedIOException("Failed getting a databaseId", e);
  90. }
  91. }
  92.  
  93. //缓存不为空则写入缓存
  94. Optional.ofNullable(this.cache).ifPresent(targetConfiguration::addCache);
  95.  
  96. //如果xmlConfigBuilder不为空 即系统有ConfigLocation 则先解析找到的xml文件信息写入config
  97. if (xmlConfigBuilder != null) {
  98. try {
  99. //先将获取到的config信息写入config
  100. xmlConfigBuilder.parse();
  101. LOGGER.debug(() -> "Parsed configuration file: '" + this.configLocation + "'");
  102. } catch (Exception ex) {
  103. throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex);
  104. } finally {
  105. ErrorContext.instance().reset();
  106. }
  107. }
  108.  
  109. //为config设置环境 以及事物处理工厂 如果没有设置默认使用Spring的事物管理
  110. targetConfiguration.setEnvironment(new Environment(this.environment,
  111. this.transactionFactory == null ? new SpringManagedTransactionFactory() : this.transactionFactory,
  112. this.dataSource));
  113.  
  114. //mapper扫描器如果不为空 即扫描mapper.xml文件的地址不为空
  115. if (this.mapperLocations != null) {
  116. if (this.mapperLocations.length == 0) {
  117. //如果长度为0 说明虽然设置了 但是没找到对应的地址
  118. LOGGER.warn(() -> "Property 'mapperLocations' was specified but matching resources are not found.");
  119. } else {
  120. //遍历所有的resource 即xml文件资源
  121. for (Resource mapperLocation : this.mapperLocations) {
  122. //判断一下空
  123. if (mapperLocation == null) {
  124. continue;
  125. }
  126. try {
  127. //为每个xml文件创建Mapper解析器
  128. XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
  129. targetConfiguration, mapperLocation.toString(), targetConfiguration.getSqlFragments());
  130. //进行解析
  131. xmlMapperBuilder.parse();
  132. } catch (Exception e) {
  133. throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
  134. } finally {
  135. ErrorContext.instance().reset();
  136. }
  137. LOGGER.debug(() -> "Parsed mapper file: '" + mapperLocation + "'");
  138. }
  139. }
  140. } else {
  141. LOGGER.debug(() -> "Property 'mapperLocations' was not specified.");
  142. }
  143.  
  144. return this.sqlSessionFactoryBuilder.build(targetConfiguration);
  145. }
  146.  
  147. }

  系统根据我们创建SqlSessionFactoryBean的 查看是否有传入Configuration ,然后根据情况分别处理,然后再将我们传入的mybatis功能组件加载到configuration中,然后如果我们设置了configLocation  则会根据这个加载对应的文件流然后解析。最后将我们加载的mapper文件,解析每个mapper.xml文件 并将信息加载到configuration  可见这个configuration保存了mybatis需要的所有信息。

  关于其中的功能组件如拦截器会在后面介绍每个组件的时候专门说明,所以这儿就不讲了,主要针对几个核心的加载方法再说明下

构造XMLConfigBuilder

  在我们没有声明configuration  而设置了configLocation时有如下代码

  1. xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
  2. //获得解析后的config
  3. targetConfiguration = xmlConfigBuilder.getConfiguration();

  这儿即和我们上面手动配置mybatis时构建的xmlConfigBuilder一模一样 ,所以我们直接看他的构造到底如何

  1. public XMLConfigBuilder(InputStream inputStream, String environment, Properties props) {
  2. this(new XPathParser(inputStream, true, props, new XMLMapperEntityResolver()), environment, props);
  3. }
  4.  
  5. private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {
      // 这儿创建了一个默认的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. }

上面代码执行了两方法,一个是新建了一个XPathParser  然后将这个解析器和环境值,参数传入了有参构造, 在有参构造中注意除了赋值操作外,还初始化了一个默认的configuration。 XPath我们都知道是一种xml处理器,所以很明显 这个XPathParse是用来解析xml文件的类,我们接着看new XPathParser(inputStream, true, props, new XMLMapperEntityResolver()) ,这儿注意传入了一个xml解析实体器XMLMapperEntityResolver  。这个处理器注意是专门用来解析mybatis的config文件和mapper文件的,可以看下其中的部分定义信息

  1. private static final String IBATIS_CONFIG_SYSTEM = "ibatis-3-config.dtd";
  2. private static final String IBATIS_MAPPER_SYSTEM = "ibatis-3-mapper.dtd";
  3. private static final String MYBATIS_CONFIG_SYSTEM = "mybatis-3-config.dtd";
  4. private static final String MYBATIS_MAPPER_SYSTEM = "mybatis-3-mapper.dtd";
  5.  
  6. private static final String MYBATIS_CONFIG_DTD = "org/apache/ibatis/builder/xml/mybatis-3-config.dtd";
  7. private static final String MYBATIS_MAPPER_DTD = "org/apache/ibatis/builder/xml/mybatis-3-mapper.dtd";

  好了 我们接着看新建xml解析器的逻辑

  1. private void commonConstructor(boolean validation, Properties variables, EntityResolver entityResolver) {
  2. this.validation = validation;
  3. this.entityResolver = entityResolver;
  4. this.variables = variables;
  5. XPathFactory factory = XPathFactory.newInstance();
  6. this.xpath = factory.newXPath();
  7. }
  8.  
  9. public XPathParser(InputStream inputStream, boolean validation, Properties variables, EntityResolver entityResolver) {
  10. //执行了一个初始化赋值方法
  11. commonConstructor(validation, variables, entityResolver);
  12. //创建我们需要的document
  13. this.document = createDocument(new InputSource(inputStream));
  14. }

  这儿终于看到了我们需要的xml对象文件 document ,后面的xmlConfigBuilder肯定也是使用类中parse所带的document对象进行解析xml节点 获取对应的配置。 我们接着看

  1. private Document createDocument(InputSource inputSource) {
  2. // important: this must only be called AFTER common constructor
  3. try {
  4. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  5. //设置一些document的通用信息
  6. factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
  7. factory.setValidating(validation);
  8.  
  9. factory.setNamespaceAware(false);
  10. factory.setIgnoringComments(true);
  11. factory.setIgnoringElementContentWhitespace(false);
  12. factory.setCoalescing(false);
  13. factory.setExpandEntityReferences(true);
  14. //创建一个文件构造器
  15. DocumentBuilder builder = factory.newDocumentBuilder();
  16. //这儿注意设置了我们刚才传入的配置文件或者mapper文件的解析器
  17. builder.setEntityResolver(entityResolver);
  18. builder.setErrorHandler(new ErrorHandler() {
  19. @Override
  20. public void error(SAXParseException exception) throws SAXException {
  21. throw exception;
  22. }
  23.  
  24. @Override
  25. public void fatalError(SAXParseException exception) throws SAXException {
  26. throw exception;
  27. }
  28.  
  29. @Override
  30. public void warning(SAXParseException exception) throws SAXException {
  31. // NOP
  32. }
  33. });
  34. //根据文件流返回包含所有xml信息的document
  35. return builder.parse(inputSource);

  到这儿  xmlConfiBuilder构造函数中就已经获取到了包含config文件所有信息的docment对象并创建对象成功,注意其中创建了一个默认的configuration。

XMLConfigBuilder.parse()方法

  在构造SqlSessionfactory中我们可以看到如下的代码

  1. //如果xmlConfigBuilder不为空 即系统有ConfigLocation 则先解析找到的xml文件信息写入config
  2. if (xmlConfigBuilder != null) {
  3. try {
  4. //先将获取到的config信息写入config
  5. xmlConfigBuilder.parse();
  6. LOGGER.debug(() -> "Parsed configuration file: '" + this.configLocation + "'");
  7. } catch (Exception ex) {
  8. throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex);
  9. } finally {
  10. ErrorContext.instance().reset();
  11. }
  12. }

  可以看到 系统在判定我们手动设置了config文件的话 最后会执行这个方法,也就是执行上面我们创建的xmlConfigBuilder方法,由此可知如果我们既创建了configuration  又设置了config文件地址,系统最终不会加载config文件中的东西。我们直接往下分析

  1. public Configuration parse() {
  2. //不能重复解析
  3. if (parsed) {
  4. throw new BuilderException("Each XMLConfigBuilder can only be used once.");
  5. }
  6. //设置解析标志
  7. parsed = true;
  8. //执行解析方法并传入config节点
  9. parseConfiguration(parser.evalNode("/configuration"));
  10. //返回这个config
  11. return configuration;
  12. }

  这儿主要设置下是否解析标志,然后拿到xml中的configuration节点信息进行解析

  1. private void parseConfiguration(XNode root) {
  2. try {
  3. //拿到properties节点 设置configuration的variables
  4. propertiesElement(root.evalNode("properties"));
  5. //拿到setting配置
  6. Properties settings = settingsAsProperties(root.evalNode("settings"));
  7. //根据对应的setting配置设置configuration的vfs
  8. loadCustomVfs(settings);
  9. //根据对应的setting配置设置configuration的日志配置
  10. loadCustomLogImpl(settings);
  11. //拿到typeAliases节点 设置configuration的别名
  12. typeAliasesElement(root.evalNode("typeAliases"));
  13. //拿到plugins节点 设置configuration的拦截器
  14. pluginElement(root.evalNode("plugins"));
  15. //拿到objectFactory节点 设置configuration的对象工厂
  16. objectFactoryElement(root.evalNode("objectFactory"));
  17. //拿到objectWrapperFactory节点 设置configuration的对象包装工厂
  18. objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
  19. //拿到reflectorFactory节点 设置configuration的反射工厂
  20. reflectorFactoryElement(root.evalNode("reflectorFactory"));
  21. //设置其他所有的setting参数到对应的mybatis中
  22. settingsElement(settings);
  23. //拿到environments节点 设置configuration的所有环境
  24. environmentsElement(root.evalNode("environments"));
  25. //拿到databaseIdProvider节点 设置configuration的数据库id
  26. databaseIdProviderElement(root.evalNode("databaseIdProvider"));
  27. //拿到typeHandlers节点 设置configuration的类型处理器
  28. typeHandlerElement(root.evalNode("typeHandlers"));
  29. //拿到mappers节点 设置configuration的mapper扫描规则并添加mapper
  30. mapperElement(root.evalNode("mappers"));
  31. } catch (Exception e) {
  32. throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
  33. }
  34. }

  这里面可以看到是根据config文件的节点信息分别设置,囿于篇幅我就不每个细说了,大概意思相信大家也能明白 这儿只着重说下mapperElement方法,这个方法主要是解析mapper文件并将mapper文件中对应的信息放入configuration中对应的装载类

  1. private void mapperElement(XNode parent) throws Exception {
  2. if (parent != null) {
  3. for (XNode child : parent.getChildren()) {
  4. //如果是package标签 即指定接口包 此时映射文件和包必须在一个文件夹下且名字要对应
  5. //这儿如果有不明白可以查看这篇博文https://www.cnblogs.com/canger/p/9911958.html
  6. if ("package".equals(child.getName())) {
  7. String mapperPackage = child.getStringAttribute("name");
  8. //根据包名添加mapper文件与接口
  9. configuration.addMappers(mapperPackage);
  10. } else {
  11. //否则都是mapper标签 mapper有三种 url resource class
  12. String resource = child.getStringAttribute("resource");
  13. String url = child.getStringAttribute("url");
  14. String mapperClass = child.getStringAttribute("class");
  15.  
  16. //第一种如果是resource类型 即引入classpath路径的相对资源 注意此方法是获取xml文件
  17. if (resource != null && url == null && mapperClass == null) {
  18. ErrorContext.instance().resource(resource);
  19. //获取mapper文件流
  20. InputStream inputStream = Resources.getResourceAsStream(resource);
  21. //创建XMLMapperBuilder并解析
  22. XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
  23. mapperParser.parse();
  24. }
  25. //第二种如果是url类型 通过url引入网络资源或者本地磁盘资源 注意此方法是获取xml文件
  26. else if (resource == null && url != null && mapperClass == null) {
  27. ErrorContext.instance().resource(url);
  28. //获取mapper文件流
  29. InputStream inputStream = Resources.getUrlAsStream(url);
  30. //创建XMLMapperBuilder并解析
  31. XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
  32. mapperParser.parse();
  33. }
  34. //第二种如果是class类型 通过class即接口找到对应的mapper.xml 注意此方法是获取接口,所以此时映射文件和包必须在一个文件夹下且名字要对应
  35. else if (resource == null && url == null && mapperClass != null) {
  36. Class<?> mapperInterface = Resources.classForName(mapperClass);
  37. //调用configuration自己的addMapper方式解析
  38. configuration.addMapper(mapperInterface);
  39. } else {
    //mapper下只能有一种节点
  40. throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
  41. }
  42. }
  43. }
  44. }
  45. }

  可以看到 根据我们在config配置文件中配置的mapper寻找策略加载,这儿主要为两种 根据接口加载,根据xml加载,根据接口的加载和xml加载类似,所以我们主要讲解下xml方式加载

XMLMapperBuilder

  在SqlSessionFactoryBean中 最后可以看到有如下代码

  1. //mapper扫描器如果不为空 即扫描mapper.xml文件的地址不为空
  2. if (this.mapperLocations != null) {
  3. if (this.mapperLocations.length == 0) {
  4. //如果长度为0 说明虽然设置了 但是没找到对应的地址
  5. LOGGER.warn(() -> "Property 'mapperLocations' was specified but matching resources are not found.");
  6. } else {
  7. //遍历所有的resource 即xml文件资源
  8. for (Resource mapperLocation : this.mapperLocations) {
  9. //判断一下空
  10. if (mapperLocation == null) {
  11. continue;
  12. }
  13. try {
  14. //为每个xml文件创建Mapper解析器
  15. XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
  16. targetConfiguration, mapperLocation.toString(), targetConfiguration.getSqlFragments());
  17. //进行解析
  18. xmlMapperBuilder.parse();
  19. } catch (Exception e) {
  20. throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
  21. } finally {
  22. ErrorContext.instance().reset();
  23. }
  24. LOGGER.debug(() -> "Parsed mapper file: '" + mapperLocation + "'");
  25. }
  26. }
  27. } else {
  28. LOGGER.debug(() -> "Property 'mapperLocations' was not specified.");
  29. }

  这里和之前的xmlConfigBuilder原理类似,都是根据传入的文件流格式根据指定的xml解析器  转化为Document对象存储xml文件的节点信息,然后执行parse()方法,将需要的信息从document中拿出来 装载进我们的configuration中,我们依旧看源代码

  由于构建xmlMapperBuilder的方式和xmlConfigBuilder几乎一致,所以这儿不再讲解,主要讲解parse()方法,我们接着看parse方法

XMLMapperBuilder.parse()方法

  1. public void parse() {
  2. //判断下是否加载了过
  3. if (!configuration.isResourceLoaded(resource)) {
  4. //拿到mapper.xml文件下mapper节点并配置
  5. configurationElement(parser.evalNode("/mapper"));
  6. //加入已装载过的资源中
  7. configuration.addLoadedResource(resource);
  8. //将mapper绑定namespace 即接口
  9. bindMapperForNamespace();
  10. }
  11.  
  12. //执行resultMap装载
  13. parsePendingResultMaps();
  14. //执行缓存装载
  15. parsePendingCacheRefs();
  16. //执行sql语句装载
  17. parsePendingStatements();
  18. }

  该方法执行几个重要的装载方法。  我们挨个说明

  configurationElement方法

  1. private void configurationElement(XNode context) {
  2. try {
  3. //获取该mapper的namespace的值 一般为接口地址
  4. String namespace = context.getStringAttribute("namespace");
  5. //判空
  6. if (namespace == null || namespace.equals("")) {
  7. throw new BuilderException("Mapper's namespace cannot be empty");
  8. }
  9. //设置当前处理的namespace
  10. builderAssistant.setCurrentNamespace(namespace);
  11. //设置当前nameSpace的缓存引用
  12. cacheRefElement(context.evalNode("cache-ref"));
  13. //设置当前nameSpace的缓存
  14. cacheElement(context.evalNode("cache"));
  15. //设置当前nameSpace的所有parameterMap
  16. parameterMapElement(context.evalNodes("/mapper/parameterMap"));
  17. //设置当前nameSpace的所有resultMap
  18. resultMapElements(context.evalNodes("/mapper/resultMap"));
  19. //设置当前nameSpace的所有sql语句
  20. sqlElement(context.evalNodes("/mapper/sql"));
  21. //设置当前nameSpace 每个sql方法的方法类型
  22. buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
  23. } catch (Exception e) {
  24. throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e);
  25. }
  26. }

  

  bindMapperForNamespace()方法

  1. private void bindMapperForNamespace() {
  2. //获取到之前设置的namespace 即接口的全限定名一般
  3. String namespace = builderAssistant.getCurrentNamespace();
  4. if (namespace != null) {
  5. Class<?> boundType = null;
  6. try {
  7. //反射获取接口
  8. boundType = Resources.classForName(namespace);
  9. } catch (ClassNotFoundException e) {
  10. //ignore, bound type is not required
  11. }
  12. if (boundType != null) {
  13. if (!configuration.hasMapper(boundType)) {
  14. // Spring may not know the real resource name so we set a flag
  15. // to prevent loading again this resource from the mapper interface
  16. // look at MapperAnnotationBuilder#loadXmlResource
  17. //添加加载过的资源
  18. configuration.addLoadedResource("namespace:" + namespace);
  19. //将当前通过namespace的获取到的接口添加到mapper中 即之前的接口添加
  20. configuration.addMapper(boundType);
  21. }
  22. }
  23. }
  24. }

  这里面主要通过namespace反射获取到接口加载到config中,这儿可以看下简要看下里面的部分逻辑

  1. public <T> void addMapper(Class<T> type) {
  2. if (type.isInterface()) {
  3. if (hasMapper(type)) {
  4. throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
  5. }
  6. boolean loadCompleted = false;
  7. try {
    //创建mapper接口 已经其对应的代理工厂
  8. knownMappers.put(type, new MapperProxyFactory<>(type));
  9. //创建对应的builder 再次加载一下
  10. MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
    //解析
  11. parser.parse();
  12. loadCompleted = true;
  13. } finally {
  14. if (!loadCompleted) {
  15. knownMappers.remove(type);
  16. }
  17. }
  18. }

    可以看到主要对namespace对应的接口创建代理工厂并存储系统缓存,然后再次加载一下,像之前的接口加载,防止还没有加载到xml文件。至于剩下的三个方法,则是分别将对应的数据加载到对应的MapperBuilderAssistant中

  1. parsePendingResultMaps();
  2. parsePendingCacheRefs();
  3. parsePendingStatements();

    到此config所需要的mapper和其他有关信息已经被全部加载进去

至此config已经参数装载完毕 最后将config作为参数传入DefaultSqlSessionFactory中创建我们所需要的SqlSessionFactory

  1. return this.sqlSessionFactoryBuilder.build(targetConfiguration);
  2.  
  3. public class SqlSessionFactoryBuilder {
  4.  
  5. public SqlSessionFactory build(Configuration config) {
  6. return new DefaultSqlSessionFactory(config);
  7. }
  8. }

完结

  我们到这儿可以理一下思路(基于spring的方式,手动方式也基本一致)

  • 创建mybatis配置文件或者自定义config
  • 创建mapper资源扫描器,扫描到所有满足我们的匹配条件的mapper信息并将资源加载到SqlSessionFactoryBean中
  • SqlSessionFactoryBean执行构建方法
  • 判断我们是否传入了configuration类,如果没有且设置了configLocation,则创建一个xmlConfigBuilder初始化一个默认的configuration,创建过程中会将config文件信息加载为Document对象以备使用
  • 为configuration设置系统功能组件
  • 判断xmlConfigBuilder是否为空,如果不为空则执行parse()方法,内部会将config文件信息即document根据功能全部解析并设置到configuration对应的值,并且会根据设置了mapper扫描策略扫描mapper.xml或者接口,最后装载mapper信息
  • 判断之前加载的mapper资源是否为空,如果不为空,则为每个资源创建xmlMapperBuilder,内部会解析mapper.xml文件为一个Document对象。然后调用parse()方法,将document中的信息设置到configuration中对应的值
  • 创建一个DefaultSqlSessionFactory返回

  

  可以看到主要就是为了创建configuration,而这个configuration也是存储所有信息的地方

  至此 我们成功的解析了config文件,或者我们自定义的config,并成功的装载进了所需要的所有参数与组件,并且拿到了所有的mapper文件信息并获取到了其namespace中对应的接口加载到config中。可以看到SqlSessionFactoryBean主要充当了构建的作用,而我们所需要的SqlSessionFactory也被创建好了。本文主要说明了两种mybatis配置模式,并根据spring模式的创建方法中四个核心的方法逐一分析,就完全了解了SqlSessionFactory中的config构建过程。下一章我们主要分析下SqlSessionFactory

    

mybatis源码探索笔记-1(构建SqlSessionFactory)的更多相关文章

  1. mybatis源码探索笔记-2(构建SqlSession并获取代理mapper)

    前言 上篇笔记我们成功的装载了Configuration,并写入了我们全部需要的信息.根据这个Configuration创建了DefaultSqlSessionFactory.本篇我们实现构建SqlS ...

  2. mybatis源码探索笔记-5(拦截器)

    前言 mybatis中拦截器主要用来拦截我们在发起数据库请求中的关键步骤.其原理也是基于代理模式,自定义拦截器时要实现Interceptor接口,并且要对实现类进行标注,声明是对哪种组件的指定方法进行 ...

  3. mybatis源码探索笔记-4(缓存原理)

    前言 mybatis的缓存大家都知道分为一级和二级缓存,一级缓存系统默认使用,二级缓存默认开启,但具体用的时候需要我们自己手动配置.我们依旧还是先看一个demo.这儿只贴出关键代码 public in ...

  4. mybatis源码探索笔记-3(使用代理mapper执行方法)

    前言 前面两章我们构建了SqlSessionFactory,并通过SqlSessionFactory创建了我们需要的SqlSession,并通过这个SqlSession获取了我们需要的代理mapper ...

  5. MyBatis源码解读(1)——SqlSessionFactory

    在前面对MyBatis稍微有点了解过后,现在来对MyBatis的源码试着解读一下,并不是解析,暂时定为解读.所有对MyBatis解读均是基于MyBatis-3.4.1,官网中文文档:http://ww ...

  6. Mybatis源码解析3——核心类SqlSessionFactory,看完我悟了

    这是昨晚的武汉,晚上九点钟拍的,疫情又一次来袭,曾经熙熙攘攘的夜市也变得冷冷清清,但比前几周要好很多了.希望大家都能保护好自己,保护好身边的人,生活不可能像你想象的那么好,但也不会像你想象的那么糟. ...

  7. MyBatis源码探索

    每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为中心的.SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获 ...

  8. mybatis源码分析(1)-----sqlSessionFactory创建

    1. 首先了解一下mybatis,包含核心jar ,以及spring相关jar. <!-- Mybatis相关组件 --> <dependency> <groupId&g ...

  9. MyBatis源码分析(4)—— Cache构建以及应用

    @(MyBatis)[Cache] MyBatis源码分析--Cache构建以及应用 SqlSession使用缓存流程 如果开启了二级缓存,而Executor会使用CachingExecutor来装饰 ...

随机推荐

  1. CentOS根目录下各目录介绍

    bin :存放普通用户可执行的指令,即使在单用户模式下也能够执行处理 boot :开机引导目录,包括Linux内核文件与开机所需要的文件 dev :设备目录,所有的硬件设备及周边均放置在这个设备目录中 ...

  2. HTML连载60-水平居中与设计一个团购界面

    一.水平居中 1.margin:0 auto在绝对定位中就失效了 2.如何让绝对定位的元素水平居中? 只需要设置绝对定位元素的left:50%:然后再设置绝对定位元素的margin-left:-元素宽 ...

  3. IntelliJ IDEA 2017.3尚硅谷-----设置字体大小行间距

  4. 欧拉降幂 (a^t)%c 模板

    #include<bits/stdc++.h> using namespace std; typedef long long ll; ll a,c,p,mod; ]; ll phi(ll ...

  5. Ubuntu16.04 anaconda3 opencv3.1.0 安装CPU版本caffe

    安装anaconda3 安装opencv3.1.0 安装依赖库 修改Makefile.config 修改Makefile 编译报错,卸载anaconda中的protobuffer: conda uni ...

  6. linux安装、使用优化、常用软件

    定制自己的ubuntu桌面系统 一.安装ubuntu 1.下载ubuntu镜像Iso文件 ubuntu官网下载:https://cn.ubuntu.com/download 2.u盘写入 (1)下载U ...

  7. 老大难的 Java ClassLoader,到了该彻底理解它的时候了

    ClassLoader 是 Java 届最为神秘的技术之一,无数人被它伤透了脑筋,摸不清门道究竟在哪里.网上的文章也是一篇又一篇,经过本人的亲自鉴定,绝大部分内容都是在误导别人.本文我带读者彻底吃透 ...

  8. GEE引擎假人系统自定义教程

    现如今传奇游戏玩家数量日渐减少.为了给服务器增加人气,很多GM在服务端中增加了自动登录和自动打怪的假人系统.由于该系统登录的假人可以自动练功,自动攻城和实现简单的对话.完全可以做到以假乱真的地步!所以 ...

  9. Windows 下 Hbuilder 真机调试(Android,iphone)

    概述:主要讲讲自己在使用 HBuilder 真机调试功能时遇到的问题,以及如何解决.Android 相对没有遇到什么大问题,在电脑安装如360手机助手就可以正常使用了,主要问题是在 iphone 上( ...

  10. 熟悉这几道 Redis 高频面试题,面试不用愁

    1.说说 Redis 都有哪些应用场景? 缓存:这应该是 Redis 最主要的功能了,也是大型网站必备机制,合理地使用缓存不仅可以加 快数据的访问速度,而且能够有效地降低后端数据源的压力. 共享Ses ...