源码解读:解析mapper.xml配置
mapper.xml配置文件结构说明
- mapper(映射配置)
-
cache – 对给定命名空间的缓存配置。
-
cache-ref – 对其他命名空间缓存配置的引用。
-
resultMap – 是最复杂也是最强大的元素,用来描述如何从数据库结果集中来加载对象。
-
parameterMap – 已被废弃!老式风格的参数映射。更好的办法是使用内联参数,此元素可能在将来被移除。 -
sql – 可被其他语句引用的可重用语句块。
-
insert – 映射插入语句
-
update – 映射更新语句
-
delete – 映射删除语句
-
select – 映射查询语句
-
源码解读
接着上一节往下走:配置mapper节点的方式有四种:package,resource,url,class 由于项目中常用的是xml,这里详细解读resource方式加载mapper
加载mapper.xml的方式
/**
* 解析mappers节点,加载mapper配置
*/
private void mapperElement(XNode parent) throws Exception {
if (parent != null) {
//变量所有的mapper.xml配置有多个
for (XNode child : parent.getChildren()) {
//如果mapper是,配置mapper的四种方式:package,resource,url,class
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");
//通过xml方式配置mapper
if (resource != null && url == null && mapperClass == null) {
ErrorContext.instance().resource(resource);
//读取配置:mapper.xml
InputStream inputStream = Resources.getResourceAsStream(resource);
//通过mapper.xml构建xml解析对象
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
//解析mapper.xml
mapperParser.parse();
//通过url的方式配置mapper
} 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();
//通过class的方式配置mapper
} 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.xml
private void configurationElement(XNode context) {
try {
//获取namespace属性
String namespace = context.getStringAttribute("namespace");
if (namespace == null || namespace.equals(