Configuration--mappers(三-8)

本篇文章,我们来讲mybatis中最核心的配置mappers.

先来看看mappers标签的用法:

<mappers>
  <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
  <mapper url="file:///var/mappers/AuthorMapper.xml"/>
  <mapper class="org.mybatis.builder.AuthorMapper"/>
  <package name="org.mybatis.builder"/>
</mappers>

我们直接来看mapperElement(root.evalNode(“mappers”))方法:

  private void mapperElement(XNode parent) throws Exception {
    if (parent != null) {
      // 遍历mappers下所有子标签
      for (XNode child : parent.getChildren()) {
        if ("package".equals(child.getName())) {
          // 当子标签为package时,使用configuration的addMappers方法添加mapper
          String mapperPackage = child.getStringAttribute("name");
          configuration.addMappers(mapperPackage);
        } else {
          String resource = child.getStringAttribute("resource");
          String url = child.getStringAttribute("url");
          String mapperClass = child.getStringAttribute("class");
          if (resource != null && url == null && mapperClass == null) {
            // 在mapper标签中使用resource时,使用XMLMapperBuilder的parse方法解析
            ErrorContext.instance().resource(resource);
            InputStream inputStream = Resources.getResourceAsStream(resource);
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
            mapperParser.parse();
          } else if (resource == null && url != null && mapperClass == null) {
            // 在mapper标签中使用url时,使用XMLMapperBuilder的parse方法解析
            ErrorContext.instance().resource(url);
            InputStream inputStream = Resources.getUrlAsStream(url);
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
            mapperParser.parse();
          } else if (resource == null && url == null && mapperClass != null) {
            // 在mapper标签中使用class时,使用configuration的addMappers方法解析
            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.");
          }
        }
      }
    }
  }

从上述代码中我们可以看出,最终是使用ConfigurationaddMappers方法或者XMLMapperBuilderparse方法去解析.

可以看出,当mapper引用的是一个类时,会使用ConfigurationaddMappers方法进行加载,当mapper引用的是一个xml文件时,会使用XMLMapperBuilderparse方法进行加载.

接下来我们将单独来讲讲这两个方法的加载过程.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值