Mybatis初始化流程分析之Mapper节点解析--转载整理

一.mappers节点解析

  • MyBatis会遍历 mappers下所有的子节点,如果当前遍历到的节点是,则MyBatis会将该包下的所有Mapper Class注册到configuration的mapperRegistry容器中。
  • 如果当前节点为 mapper,则会依次获取resource、url、class属性,解析映射文件,并将映射文件对应的Mapper Class注册到configuration的mapperRegistry容器中。
  • 创建XMLMapperBuilder对象并执行parse()方法

1.mappers节点的解析

  private void mapperElement(XNode parent) throws Exception {
   
  if (parent != null) {
   
    // 遍历<mappers>下所有子节点
    for (XNode child : parent.getChildren()) {
   
      // 如果当前节点为<package>
      if ("package".equals(child.getName())) {
   
        // 获取<package>的name属性(该属性值为mapper class所在的包名)
        String mapperPackage = child.getStringAttribute("name");
        // 将该包下的所有Mapper Class注册到configuration的mapperRegistry容器中
        configuration.addMappers(mapperPackage);
      } 
      // 如果当前节点为<mapper>
      else {
   
        // 依次获取resource、url、class属性
        String resource = child.getStringAttribute("resource");
        String url = child.getStringAttribute("url");
        String mapperClass = child.getStringAttribute("class");
        // 解析resource属性(Mapper.xml文件的路径)
        if (resource != null && url == null && mapperClass == null) {
   
          ErrorContext.instance().resource(resource);
          // 将Mapper.xml文件解析成输入流
          InputStream inputStream = Resources.getResourceAsStream(resource);
          // 使用XMLMapperBuilder解析Mapper.xml,并将Mapper Class注册进configuration对象的mapperRegistry容器中
          XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
          mapperParser.parse();
        } 
        // 解析url属性(Mapper.xml文件的路径)
        else if (resource == null && url != null && mapperClass == null) {
   
          ErrorContext.instance().resource(url);
          InputStream inputStream = Resources.getUrlAsStream(url);
          XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
          mapperParser.parse()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

了-凡

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值