mybatis源碼分析系列:
- mybatis源碼看這一遍就夠了(1)| 前言
- mybatis源碼看這一遍就夠了(2)| getMapper
- mybatis源碼看這一遍就夠了(3)| Configuration及解析配置文件
- mybatis源碼看這一遍就夠了(4)| SqlSession.select調用分析
- mybatis源碼看這一遍就夠了(5)| 與springboot整合
這一章我們來針對上一章遺留的問題進行分析,包括mappedStatements、knownMappers從何而來,Configuration做了些什麼?
我們直接從我們第一章的例子入手:
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("configuration.xml"));
這麼短短的一句一句話究竟做了哪些不爲人知的事,我們點進SqlSessionFactoryBuilder.build()方法:
首先構造初始化了XMLConfigBuilder,然後調用parser.parse()開始解析和返回configuration對象:
可以看到parseConfiguration解析我們的配置文configuration.xml的<configuration>節點下的數據:
private void parseConfiguration(XNode root) {
try {
//issue #117 read properties first
propertiesElement(root.evalNode("properties"));
Properties settings = settingsAsProperties(root.evalNode("settings"));
loadCustomVfs(settings);
loadCustomLogImpl(settings);
typeAliasesElement(root.evalNode("typeAliases"));
pluginElement(root.evalNode("plugins"));
objectFactoryElement(root.evalNode("objectFactory"));
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
reflectorFactoryElement(root.evalNode("reflectorFactory"));
settingsElement(settings);
// read it after objectFactory and objectWrapperFactory issue #631
environmentsElement(root.evalNode("environments"));
databaseIdProviderElement(root.evalNode("databaseIdProvider"));
typeHandlerElement(root.evalNode("typeHandlers"));
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
看到這些節點名是不是很熟悉,它就是configuration配置文件的節點,比如我們配置的environments和mappers:
那我們下面就只看我們demo裏這兩個用到的節點,其他都是大同小異,我們先看下environments節點的解析:
這裏圈紅位置就是獲取dataSource節點下的配置數據,然後將其解析成Properties然後放入DataSource裏面
然後將構建好的 DataSource放入Environment對象中,緊接着就是將Environment放在configuration對象裏。
好了下面說下mapper節點的解析mapperElement(root.evalNode("mappers")):
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.");
}
}
}
}
}
String resource = child.getStringAttribute("resource");
這句不正是解析configuration.xml裏配置的
這裏拿到Mapper的sql配置文件名mybatis/UserMapper.xml;緊接着就是解析UserMapper.xml文件
解析UserMapper.xml文件mapper節點
調用configurationElement:
private void configurationElement(XNode context) {
try {
String namespace = context.getStringAttribute("namespace");
if (namespace == null || namespace.equals("")) {
throw new BuilderException("Mapper's namespace cannot be empty");
}
builderAssistant.setCurrentNamespace(namespace);
cacheRefElement(context.evalNode("cache-ref"));
cacheElement(context.evalNode("cache"));
parameterMapElement(context.evalNodes("/mapper/parameterMap"));
resultMapElements(context.evalNodes("/mapper/resultMap"));
sqlElement(context.evalNodes("/mapper/sql"));
buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
} catch (Exception e) {
throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e);
}
}
這裏面就是對UserMapper.xml文件的解析,可以看到些熟悉的字眼,比如我們配的namespace,還有就是select:
我們進入buildStatementFromContext(context.evalNodes("select|insert|update|delete")):
遍歷拿到的所有select|insert|update|delete節點,然後調用statementParser.parseStatementNode()進行解析:
public void parseStatementNode() {
String id = context.getStringAttribute("id");
String databaseId = context.getStringAttribute("databaseId");
if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
return;
}
String nodeName = context.getNode().getNodeName();
SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));
boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect);
boolean useCache = context.getBooleanAttribute("useCache", isSelect);
boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false);
// Include Fragments before parsing
XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);
includeParser.applyIncludes(context.getNode());
String parameterType = context.getStringAttribute("parameterType");
Class<?> parameterTypeClass = resolveClass(parameterType);
String lang = context.getStringAttribute("lang");
LanguageDriver langDriver = getLanguageDriver(lang);
// Parse selectKey after includes and remove them.
processSelectKeyNodes(id, parameterTypeClass, langDriver);
// Parse the SQL (pre: <selectKey> and <include> were parsed and removed)
KeyGenerator keyGenerator;
String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX;
keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true);
if (configuration.hasKeyGenerator(keyStatementId)) {
keyGenerator = configuration.getKeyGenerator(keyStatementId);
} else {
keyGenerator = context.getBooleanAttribute("useGeneratedKeys",
configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))
? Jdbc3KeyGenerator.INSTANCE : NoKeyGenerator.INSTANCE;
}
SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString()));
Integer fetchSize = context.getIntAttribute("fetchSize");
Integer timeout = context.getIntAttribute("timeout");
String parameterMap = context.getStringAttribute("parameterMap");
String resultType = context.getStringAttribute("resultType");
Class<?> resultTypeClass = resolveClass(resultType);
String resultMap = context.getStringAttribute("resultMap");
String resultSetType = context.getStringAttribute("resultSetType");
ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType);
if (resultSetTypeEnum == null) {
resultSetTypeEnum = configuration.getDefaultResultSetType();
}
String keyProperty = context.getStringAttribute("keyProperty");
String keyColumn = context.getStringAttribute("keyColumn");
String resultSets = context.getStringAttribute("resultSets");
builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
resultSetTypeEnum, flushCache, useCache, resultOrdered,
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
}
這裏面就是對整個mapper文件進行了解析操作,包括拿到id;sql語句呀等等,然後將其組裝成MappedStatement:
builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
resultSetTypeEnum, flushCache, useCache, resultOrdered,
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
進入builderAssistant.addMappedStatement方法下面部分代碼:
id = applyCurrentNamespace(id, false);
boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, id, sqlSource, sqlCommandType)
.resource(resource)
.fetchSize(fetchSize)
.timeout(timeout)
.statementType(statementType)
.keyGenerator(keyGenerator)
.keyProperty(keyProperty)
.keyColumn(keyColumn)
.databaseId(databaseId)
.lang(lang)
.resultOrdered(resultOrdered)
.resultSets(resultSets)
.resultMaps(getStatementResultMaps(resultMap, resultType, id))
.resultSetType(resultSetType)
.flushCacheRequired(valueOrDefault(flushCache, !isSelect))
.useCache(valueOrDefault(useCache, isSelect))
.cache(currentCache);
ParameterMap statementParameterMap = getStatementParameterMap(parameterMap, parameterType, id);
if (statementParameterMap != null) {
statementBuilder.parameterMap(statementParameterMap);
}
MappedStatement statement = statementBuilder.build();
configuration.addMappedStatement(statement);
return statement;
獲取id,有namespace+.id組成id值
public String applyCurrentNamespace(String base, boolean isReference) {
...省略
return currentNamespace + "." + base;
}
new MappedStatement.Builder創建了一個MappedStatement,然後對解析出來的節點數據進行賦值放在MappedStatement:
最後將其 MappedStatement放入configuration對象中
其實這裏就是調用addMappedStatement方法將其key爲namespace+.id,value爲MappedStatement放入Map<String, MappedStatement> mappedStatements,到這裏是不是就回答了上一章mybatis源碼看這一遍就夠了(2)中間提到的mappedStatements哪裏來的問題。也回答了configuration這個對象究竟做了些啥這個問題。
然後我們繼續回到上面XMLMapperBuilder.parse這裏:
public void parse() {
if (!configuration.isResourceLoaded(resource)) {
configurationElement(parser.evalNode("/mapper"));
configuration.addLoadedResource(resource);
bindMapperForNamespace();
}
parsePendingResultMaps();
parsePendingCacheRefs();
parsePendingStatements();
}
解析完mapper文件接着調用bindMapperForNamespace():
判斷configuration.hasMapper(boundType)是否已經解析過有存在:
當然我們這裏還是沒有放入knownMappers這個map裏面的,那麼久進入configuration.addMapper(boundType):
到這裏是不是可以看到創建MapperProxyFactory<>(type),key爲type然後放入knownMappers這個map裏面,這個不就回答了我們上一章的問題knownMappersmybatis源碼看這一遍就夠了(2)從何而來嗎。
好了,其他的解析我就不再贅述了,因爲太多內容,其實都是大同小異的東西,大家可以自己跟一下源碼很快就能get到的。
上一章還有遺留一個問題未解答,sqlSession.selectList這一步究竟做了啥,這和jdbc又有什麼關係,我們下一章mybatis源碼看一遍就夠了(4)繼續分析