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的加载流程深入讲解


版权声明:本文为mmklo原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。