MyBatis加载Mapper映射文件的方式

MyBatis加载Mapper的映射文件的方式

我们都知道MyBatis是一款半自动的ORM框架,它的特点就是具有灵活的sql操作
MyBatis是利用mapper的映射文件,来将数据库的中字段与Java的属性关联。完成对数据库的操作
问题来了,MyBatis加载Mapper映射文件的方式有几种?
观察MyBatis的底层源码发现
通过快速搜索XMLConfigMapper这个类,这是MyBatis底层封装的用于规范MyBatis核心配置文件的类
,在里面我们可以发现为什么MyBatis里有着严格的标签书写顺序。(不是我这里所说的)
往下找到**mapperElement **这个方法
在这里插入图片描述

private void mapperElement(XNode parent) throws Exception {
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
        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");
          if (resource != null && url == null && mapperClass == null) {
            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) {
            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) {
            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.");
          }
        }
      }
    }
  }

从这个方法中我们就可以发现mapper的加载方式共有四种:

  1. package
  2. resource
  3. url
  4. class

优先级,执行顺序也就自然明了

🔥🔥注意:

package方式加载只需要name一个属性;
一个mapper子节点有且只能有url、resource、class三个属性中其中一个,否则会抛出异常;
mapperElement解析两种mappers子节点,主要代码我分成了4个部分

如果想更加深入的详细了解:参考:Mybatis对mapper的加载流程深入讲解

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

@WAT

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

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

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

打赏作者

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

抵扣说明:

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

余额充值