小胡的博客

  • 首页
  • 文章归档
  • 默认分类
  • 关于页面

  • 搜索

003-mapper解析

发表于 2020-04-09 | 分类于 mybaits | 0 | 阅读次数 18045

mapperElement

private void mapperElement(XNode parent) throws Exception {
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
        // 如果是直接给定一个包名,那么代表 全是mapper,没有xml
        if ("package".equals(child.getName())) {
          String mapperPackage = child.getStringAttribute("name");
          configuration.addMappers(mapperPackage);
        } else {
          String resource = child.getStringAttribute("resource");
          String url = child.getStringAttribute("url");
          String mapperClass = child.getStringAttribute("class");
          // resource  xml
          if (resource != null && url == null && mapperClass == null) {
            // todo  以后探讨下这是撒
            ErrorContext.instance().resource(resource);
            // input 流
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //  建造者模式构建解析器
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
            // 解析, 重头戏
            mapperParser.parse();
          } else if (resource == null && url != null && mapperClass == null) {
            // url
            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<?> 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.");
          }
        }
      }
    }
  }

从上可以看出,支持2中方式,

<mappers>
  <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
  <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
  <mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>

第二种

<!-- 将包内的映射器接口实现全部注册为映射器 -->
<mappers>
  <package name="org.mybatis.builder"/>
</mappers>
  • 本文作者: 小胡
  • 本文链接: http://myblog.run/archives/003-mapper解析
  • 版权声明: 本博客所有文章除特别声明外,均采用CC BY-NC-SA 3.0 许可协议。转载请注明出处!
002-mybatisXml解析
  • 文章目录
  • 站点概览
小胡

小胡

5 日志
5 分类
0 标签
RSS
Creative Commons
© 2026 小胡
由 Halo 强力驱动
|
主题 - NexT.Gemini v5.1.4
渝ICP备20006930号