您的位置 首页 java

聊聊Mybatis的初始化之Mapper.xml映射文件的解析

聊聊 Mybatis 的初始化之Mapper.xml映射文件的解析

解析完全局配置文件后接下来就是解析Mapper文件了,它是通过XMLMapperBuilder来进行解析的

解析Mapper文件入口

XMLMapperBuilder的parse()方法:

 public  void  parse() {
     if  (!configuration.isResourceLoaded(resource)) {
      configurationElement(parser. eval Node("/mapper"));
      configuration.addLoadedResource(resource);
      bindMapperForNamespace();
    }

    parsePendingResultMaps();
    parsePendingCacheRefs();
    parsePendingStatements();
  }  
 <resultMap>
< Cache -ref>
  

重点看一下XMLMapperBuilder类的configurationElement()方法

解析Mapper文件

MLMapperBuilder类的configurationElement()方法:

  private  void configurationElement(XNode context) {
    try {
       String  namespace = context.getStringAttribute("namespace");
      if (namespace == null || namespace.isEmpty()) {
        throw new Builder Exception ("Mapper's namespace cannot be empty");
      }
      builderAssistant.setCurrentNamespace(namespace);
      cacheRefElement(context.evalNode("cache-ref"));
      cacheElement(context.evalNode("cache"));
      parameterMapElement(context.evalNodes("/mapper/parameterMap"));
      resultMapElements(context.evalNodes("/mapper/resultMap"));
       SQL Element(context.evalNodes("/mapper/ Sql "));
      buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e);
    }
  }  
  1. 解析Mapper文件的namespace属性
  2. 解析 <cache-ref> 标签,这个标签是用来引用别的Cache缓存
  3. 解析 <cache> 标签,这个标签是用来启用Mybatis的二级缓存的,一级缓存是默认开启的,在这个方法里解析到MapperBuilderAssistant类完成Cache的创建,保存在Configuration.caches的集合中,集合的key是namespace,值是Cache对象
  4. 解析 <parameterMap> 标签,这个标签已经废弃了,一般使用 parameterType 来定义参数的类名
  5. 解析 <resultMap> 标签,这个标签是结果映射,它标签下的所有子标签解析后保存在ResultMap对象中,具体会解析先获取resultMap中的 type ,type是结果集映射成的 java 对象,然后解析resultMap标签的子标签,包括 <constructor>、<id>、<result>、<collection> 等标签,这些标签生成ResultMapping对象,然后获取id extends等属性,构建ResultMapResolver对象,创建ResultMap对象保存到Configuration.resultMaps集合中
  6. 解析 sql 标签,这个标签是用来定义重复的sql片段的,解析出保存在Configuration.sqlFragments中
  7. 解析 <select>、<insert>、<update>、<delete> 等SQL节点,这些标签大家肯定就熟悉了,就是我们的增删改查的 sql语句 ,通过XMLStatementBuilder来进行解析,它会先解析 < include > 标签,然后解析 <selectKey> 标签,保存到Configuration.keyGenerators集合中,最后通过LanguageDriver.createSqlSource()方法创建SqlSource对象,构建MappedStatement对象,MappedStatement的sqlSource记录sql语句,sqlCommandType记录SQL语句的类型,保存在Configuration.mappedStatements集合中

总结

这篇文章主要讲了Mapper映射文件的解析,包括namespace、cache、resultMap、sql等标签,最终这些信息都会保存到Configuration中,理解Mapper的映射逻辑还是非常重要的,因为我们开发的时候主要就是编写Mapper文件。

文章来源:智云一二三科技

文章标题:聊聊Mybatis的初始化之Mapper.xml映射文件的解析

文章地址:https://www.zhihuclub.com/184783.shtml

关于作者: 智云科技

热门文章

网站地图