mybatis源码-解析配置文件(四)之配置文件Mapper解析

时间:2022-09-26 00:25:54

mybatis源码-解析配置文件(三)之配置文件Configuration解析 中, 讲解了 Configuration 是如何解析的。

其中, mappers作为configuration节点的一部分配置, 在本文章中, 我们讲解解析mappers节点, 即 xxxMapper.xml 文件的解析。

1 解析入口

在解析 mybatis-config.xml 时, 会进行解析 xxxMapper.xml 的文件。

mybatis源码-解析配置文件(四)之配置文件Mapper解析

在图示流程的 XMLConfigBuilder.parse() 函数中, 该函数内部, 在解析 mappers 节点时, 会调用 mapperElement(root.evalNode("mappers"))

private void mapperElement(XNode parent) throws Exception {
if (parent != null) {
// 遍历其子节点
for (XNode child : parent.getChildren()) {
// 如果配置的是包(packege)
if ("package".equals(child.getName())) {
String mapperPackage = child.getStringAttribute("name");
configuration.addMappers(mapperPackage);
} else {
// 如果配置的是类(有三种情况 resource / class / url)
String resource = child.getStringAttribute("resource");
String url = child.getStringAttribute("url");
String mapperClass = child.getStringAttribute("class");
// 配置一:使用 resource 类路径
if (resource != null && url == null && mapperClass == null) {
ErrorContext.instance().resource(resource);
InputStream inputStream = Resources.getResourceAsStream(resource);
// 创建 XMLMapperBuilder 对象
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
// 解析 xxxMapper.xml
mapperParser.parse();
// 配置二: 使用 url 绝对路径
} else if (resource == null && url != null && mapperClass == null) {
ErrorContext.instance().resource(url);
InputStream inputStream = Resources.getUrlAsStream(url);
// 创建 XMLMapperBuilder 对象
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
// 解析 xxxMapper.xml
mapperParser.parse();
// 配置三: 使用 class 类名
} else if (resource == null && url == null && mapperClass != null) {
// 通过反射创建对象
Class<?> mapperInterface = Resources.classForName(mapperClass);
// 添加
configuration.addMapper(mapperInterface);
} else {
throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
}
}
}
}
}

从以上源码中可以发现, 配置时, 一种是通过包的方式, 一种是通过指定文件的方式。

但不管是怎么配置, 最后的找落点都是 xxxMapper.xml 文件的解析。

2 解析

包扫描时, 会加载指定包下的文件, 最终会调用

private void loadXmlResource() {
// 判断是否已经加载过
if (!configuration.isResourceLoaded("namespace:" + type.getName())) {
String xmlResource = type.getName().replace('.', '/') + ".xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(type.getClassLoader(), xmlResource);
} catch (IOException e) {
// ignore, resource is not required
}
if (inputStream != null) {
XMLMapperBuilder xmlParser = new XMLMapperBuilder(inputStream, assistant.getConfiguration(), xmlResource, configuration.getSqlFragments(), type.getName());
// 解析
xmlParser.parse();
}
}
}

因此, 不管是包扫描还是文件扫描, 最终都经历一下 xmlParser.parse() 解析过程。

2.1 解析流程

解析 xxxMapper.xml 文件的是下面这个函数,解析 mapper 节点。

  public void parse() {
// 判断是否已经加载过
if (!configuration.isResourceLoaded(resource)) {
// 解析 <mapper> 节点
configurationElement(parser.evalNode("/mapper"));
// 标记一下,已经加载过了
configuration.addLoadedResource(resource);
// 绑定映射器到namespace
bindMapperForNamespace();
}
// 处理 configurationElement 中解析失败的<resultMap>
parsePendingResultMaps();
// 处理configurationElement 中解析失败的<cache-ref>
parsePendingCacheRefs();
// 处理 configurationElement 中解析失败的 SQL 语句
parsePendingStatements();
}

大致流程

  1. 解析调用 configurationElement() 函数来解析各个节点
  2. 标记传入的文件已经解析了
  3. 绑定文件到相应的 namespace, 所以 namespace 需要是唯一的
  4. 处理解析失败的节点

2.2 解析各个节点

  private void configurationElement(XNode context) {
try {
// 获取namespace属性, 其代表者这个文档的标识
String namespace = context.getStringAttribute("namespace");
if (namespace == null || namespace.equals("")) {
throw new BuilderException("Mapper's namespace cannot be empty");
}
builderAssistant.setCurrentNamespace(namespace);
// 解析 <cache-ref> 节点
cacheRefElement(context.evalNode("cache-ref"));
// 解析 <cache> 节点
cacheElement(context.evalNode("cache"));
// 解析 </mapper/parameterMap> 节点
parameterMapElement(context.evalNodes("/mapper/parameterMap"));
// 解析 </mapper/resultMap> 节点
resultMapElements(context.evalNodes("/mapper/resultMap"));
// 解析 </mapper/sql> 节点
sqlElement(context.evalNodes("/mapper/sql"));
// 解析 select|insert|update|delet 节点
buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
} catch (Exception e) {
throw new BuilderException("Error parsing Mapper XML. Cause: " + e, e);
}
}

为了避免篇幅太长, 在此就不深入讲解各个解析过程, 后续会开专门的章节。

一起学 mybatis

你想不想来学习 mybatis? 学习其使用和源码呢?那么, 在博客园关注我吧!!

我自己打算把这个源码系列更新完毕, 同时会更新相应的注释。快去 star 吧!!

mybatis最新源码和注释

mybatis源码-解析配置文件(四)之配置文件Mapper解析

mybatis源码-解析配置文件(四)之配置文件Mapper解析的更多相关文章

  1. Mybatis源码详解系列&lpar;三&rpar;--从Mapper接口开始看Mybatis的执行逻辑

    简介 Mybatis 是一个持久层框架,它对 JDBC 进行了高级封装,使我们的代码中不会出现任何的 JDBC 代码,另外,它还通过 xml 或注解的方式将 sql 从 DAO/Repository ...

  2. mybatis源码分析(二)------------配置文件的解析

    这篇文章中,我们将讲解配置文件中 properties,typeAliases,settings和environments这些节点的解析过程. 一 properties的解析 private void ...

  3. mybatis源码学习(四):动态SQL的解析

    之前的一片文章中我们已经了解了MappedStatement中有一个SqlSource字段,而SqlSource又有一个getBoundSql方法来获得BoundSql对象.而BoundSql中的sq ...

  4. mybatis源码分析(四)---------------代理对象的生成

    在mybatis两种开发方式这边文章中,我们提到了Mapper动态代理开发这种方式,现在抛出一个问题:通过sqlSession.getMapper(XXXMapper.class)来获取代理对象的过程 ...

  5. MyBatis源码分析(四):SQL执行过程分析

    一.获取Mapper接口的代理 根据上一节,Mybatis初始化之后,利用sqlSession(defaultSqlSession)的getMapper方法获取Mapper接口 1 @Override ...

  6. mybatis 源码分析(四)一二级缓存分析

    本篇博客主要讲了 mybatis 一二级缓存的构成,以及一些容易出错地方的示例分析: 一.mybatis 缓存体系 mybatis 的一二级缓存体系大致如下: 首先当一二级缓存同时开启的时候,首先命中 ...

  7. mybatis源码探索笔记-3&lpar;使用代理mapper执行方法&rpar;

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

  8. mybatis源码学习(一):Mapper的绑定

    在mybatis中,我们可以像下面这样通过声明对应的接口来绑定XML中的mapper,这样可以让我们尽早的发现XML的错误. 定义XML: <?xml version="1.0&quo ...

  9. 【mybatis源码学习】与spring整合Mapper接口执行原理

    一.重要的接口 org.mybatis.spring.mapper.MapperFactoryBean MapperScannerConfigurer会向spring中注册该bean,一个mapper ...

  10. MyBatis 源码分析 - 映射文件解析过程

    1.简介 在上一篇文章中,我详细分析了 MyBatis 配置文件的解析过程.由于上一篇文章的篇幅比较大,加之映射文件解析过程也比较复杂的原因.所以我将映射文件解析过程的分析内容从上一篇文章中抽取出来, ...

随机推荐

  1. javascript标识符

    标识符,就是指变量.函数.属性的名字,或者函数的参数. 规则 1.第一个字符必须是一个字母.下划线或是美元符号($) 2.其他字符可以是字母.下划线.美元符号或数字 3.不能是关键字和保留字 4.区分 ...

  2. NDK&lpar;4&rpar;&quot&semi;Unresolved inclusion jni&period;h”的解决方法

    参考 :  http://blog.csdn.net/zhubin215130/article/details/39347873 3种解决办法: 一,重新初始化eclipse对该project的nat ...

  3. c&num;加密汇总【粘】

    方法一: SHA1[不可逆]     //须添加对System.Web的引用     using System.Web.Security;           ...           /// &l ...

  4. 问题记录:spark读取hdfs文件出错

    错误信息: scala> val file = sc.textFile("hdfs://kit-b5:9000/input/README.txt") 13/10/29 16: ...

  5. wxpython 拖动界面时进入假死状态(未响应)解决方法

    场景:在一个事件中调用一个函数,但是这个函数执行的时间非常的长,此过程中拖动界面的时候会使得界面进入未响应状态,直到函数执行完才可以ok 解决方法: 在调用函数的时候使用多线程调用 import th ...

  6. MyEclipse中jquery文件报错

  7. webuploader限制只上传图片文件

    // 如果上传的文件不为图片格式, 那么就提示"上传文件格式不正确" if (file.type!="image/jpg" && file.ty ...

  8. linux 怎么与网络对时

    首先来了解下面几个知识点:1. date命令:#date显示系统时间2.hwclock命令 (即hardwareclock系统硬件时间)#hwclock显示硬件时间#hwclock -w将系统时间写入 ...

  9. 【CodeChef】Querying on a Grid(分治,最短路)

    [CodeChef]Querying on a Grid(分治,最短路) 题面 Vjudge CodeChef 题解 考虑分治处理这个问题,每次取一个\(mid\),对于\(mid\)上的三个点构建最 ...

  10. 搜素表脚本&period;vbs

    Set oFso = CreateObject("Scripting.FileSystemObject")dim path(30)dim name(30)'说明书表头有15列:补丁 ...