0
点赞
收藏
分享

微信扫一扫

为什么MyBatis配置映射器只有四种


以下代码为MyBatis源码:

//解析mappers标签
mapperElement(root.evalNode("mappers"));

private void mapperElement(XNode parent) throws Exception {

if (parent != null) {
//循环遍历我们mappers标签下面的所有子标签
for (XNode child : parent.getChildren()) {

//方式一:通过package方式配置映射器
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方式配置映射器
if (resource != null && url == null && mapperClass == null) {
ErrorContext.instance().resource(resource);
try (InputStream inputStream = Resources.getResourceAsStream(resource)) {
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
mapperParser.parse();
}

//方式三:使用url的方式配置映射器
} else if (resource == null && url != null && mapperClass == null) {
ErrorContext.instance().resource(url);
try (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.");
}
}
}
}
}

A mapper element may only specify a url, resource or class, but not more than one.


图示标签代码,为mybatis-config.xml配置文件中,mappers标签的底层定义

为什么MyBatis配置映射器只有四种_xml配置


结论:

  1. MyBatis配置映射器的方式只有四种方式,如果不属于四种之一就会抛出异常
  2. package配置的方式和另外三种配置方式在代码逻辑上属于两类
  3. mappers标签内部,可以使用不同的进行配置mapper映射器


举报

相关推荐

0 条评论