notNull(dataSource, “Property ‘dataSource’ is required”);
notNull(sqlSessionFactoryBuilder, “Property ‘sqlSessionFactoryBuilder’ is required”);
this.sqlSessionFactory = buildSqlSessionFactory();
}
前面有解析Mybatis-config.xml配置文件的,这里不跟了,]代码太多了,省略了
重点看下怎么解析我们自定义的xml的
循环mapperLocation(xml文件路径),拿到就是单个xml文件
构建XMLMapperBuilder 去解析
//…省略
if (this.mapperLocations != null) {
if (this.mapperLocations.length == 0) {
LOGGER.warn(() -> “Property ‘mapperLocations’ was specified but matching resources are not found.”);
} else {
for (Resource mapperLocation : this.mapperLocations) {
if (mapperLocation == null) {
continue;
}
try {
/**
- 真正的循环我们的mapper.xml文件
*/
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
targetConfiguration, mapperLocation.toString(), targetConfiguration.getSqlFragments());
xmlMapperBuilder.parse();
} catch (Exception e) {
throw new NestedIOException(“Failed to parse mapping resource: '” + mapperLocation + “'”, e);
} finally {
ErrorContext.instance().reset();
}
LOGGER.debug(() -> “Parsed mapper file: '” + mapperLocation + “'”);
}
}
}
进入xmlMapperBuilder.parse();
public void parse() {
/**
- 判断当前的Mapper是否被加载过
*/
if (!configuration.isResourceLoaded(resource)) {
/**
-
真正的解析我们的
*/
configurationElement(parser.evalNode(“/mapper”));
/**
- 把资源保存到我们Configuration中
*/
configuration.addLoadedResource(resource);
bindMapperForNamespace();
}
parsePendingResultMaps();
parsePendingCacheRefs();
parsePendingStatements();
}
进入configurationElement(parser.evalNode("/mapper"));
开始解析xml文件,里面的属性都会解析(nameSpace,resultMap,mapper…)
private void configurationElement(XNode context) {
try {
/**
-
解析我们的namespace属性
*/
String namespace = context.getStringAttribute(“namespace”);
if (namespace == null || namespace.equals(“”)) {
throw new BuilderException(“Mapper’s namespace cannot be empty”);
}
/**
- 保存我们当前的namespace 并且判断接口完全类名==namespace
*/
builderAssistant.setCurrentNamespace(namespace);
/**
-
解析我们的缓存引用
-
说明我当前的缓存引用和DeptMapper的缓存引用一致
解析到org.apache.ibatis.session.Configuration#cacheRefMap<当前namespace,ref-namespace>
异常下(引用缓存未使用缓存):org.apache.ibatis.session.Configuration#incompleteCacheRefs
*/
cacheRefElement(context.evalNode(“cache-ref”));
/**
-
解析我们的cache节点
解析到:org.apache.ibatis.session.Configuration#caches
org.apache.ibatis.builder.MapperBuilderAssistant#currentCache
*/
cacheElement(context.evalNode(“cache”));
/**
- 解析paramterMap节