Mybatis 初始化是由
SqlSessionFactoryBuilder
來完成的,主要的工作解析XML檔案,并将解析的類容封裝到
Configuration
類中,最後将
Configuration
類封裝到
SqlSessionFactory
中并傳回,自此初始化完成。
完成對XML檔案解析的是
XMLConfigBuilder
、
XMLMapperBuilder
、
XMLStatementBuilder
三個類來完成:
- XMLConfigBuilder:負責全局配置檔案(mybatis-config.xml)中除了
節點的解析。mappers
- XMLMapperBuilder:負責解析
映射檔案中xxxMapper.xml
、cache-ref
、cache
、parameterMap
、resultMap
節點;根據 namespace 将Mapper接口的動态代理工廠注冊到 MapperRegistry 中。sql
- XMLStatementBuilder:負責解析
映射檔案中SQL語句節點,如:xxxMapper.xml
、select
、insert
、update
。delete
- XMLScriptBuilder:負責解析SQL腳本,然後封裝成
。SqlSource
Mybatis 初始化流程
SqlSessionFactoryBuilder
SqlSessionFactoryBuilder會将解析任務托給XMLConfigBuilder類,源碼如下:
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
// 委托給XMLConfigBuilder去解析配置檔案
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
// 開始解析
return build(parser.parse());
}
...
}
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
XMLConfigBuilder
負責全局配置檔案(mybatis-config.xml)中除了mappers節點的解析。解析節點委托給XMLMapperBuilder解析器。
private void parseConfiguration(XNode root) {
try {
//issue #117 read properties first
// 解析<properties>節點
propertiesElement(root.evalNode("properties"));
// 解析<settings>節點
Properties settings = settingsAsProperties(root.evalNode("settings"));
loadCustomVfs(settings);
loadCustomLogImpl(settings);
// 解析<typeAliases>節點
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"));
// 解析<mappers>節點
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
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來解析映射檔案
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來解析映射檔案
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.");
}
}
}
}
}
XMLMapperBuilder
負責解析xxxMapper.xml映射檔案中cache-ref、cache、parameterMap、resultMap、sql節點;根據 namespace 将Mapper接口的動态代理工廠(MapperProxyFactory)注冊到 MapperRegistry 中。
public void parse() {
// 防止重複解析
if (!configuration.isResourceLoaded(resource)) {
// 解析xxxMapper.xml 映射檔案中的 mapper節點
configurationElement(parser.evalNode("/mapper"));
// 标記為已經加載過
configuration.addLoadedResource(resource);
// 根據 namespace 将Mapper接口的動态代理工廠注冊到 MapperRegistry 中
bindMapperForNamespace();
}
// 兜底
parsePendingResultMaps();
parsePendingCacheRefs();
parsePendingStatements();
}
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);
// 解析<cache-ref>節點
cacheRefElement(context.evalNode("cache-ref"));
// 解析<cache>節點
cacheElement(context.evalNode("cache"));
// 解析<parameterMap>節點
parameterMapElement(context.evalNodes("/mapper/parameterMap"));
// 解析<resultMap>節點
resultMapElements(context.evalNodes("/mapper/resultMap"));
sqlElement(context.evalNodes("/mapper/sql"));
// 解析<select|insert|update|delete>節點
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);
}
}
private void buildStatementFromContext(List<XNode> list) {
if (configuration.getDatabaseId() != null) {
buildStatementFromContext(list, configuration.getDatabaseId());
}
buildStatementFromContext(list, null);
}
private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) {
for (XNode context : list) {
// 解析<select|insert|update|delete>節點委托給 XMLStatementBuilder
final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);
try {
statementParser.parseStatementNode();
} catch (IncompleteElementException e) {
configuration.addIncompleteStatement(statementParser);
}
}
}
XMLStatementBuilder
負責解析xxxMapper.xml映射檔案中SQL語句節點,如:select、insert、update、delete。解析<select|insert|update|delete>節點委托給XMLStatementBuilder解析器。
public void parseStatementNode() {
String id = context.getStringAttribute("id");
String databaseId = context.getStringAttribute("databaseId");
if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
return;
}
// 根據節點的名稱來判斷SQL語句的類型(select|insert|update|delete)
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
// 解析<include>節點
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.
// 解析<selectKey>節點,并在XML中删除<selectKey>節點
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;
}
// 解析SQL語句,然後封裝成SqlSource
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");
// 使用建造者模式建構MappedStatement對象
builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
resultSetTypeEnum, flushCache, useCache, resultOrdered,
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
}
Mybatis 初始化流程圖
核心資料結構類
Configuration
Configuration
其實就是XML配置檔案的Java形态,Configuration是單例的,生命周期是應用級的;
ResultMap
對應xxxMapper.xml映射檔案中的
resultMap
節點。
<resultMap>
節點中的子節點使用
ResultMapping
來封裝,如:
<id>
、
<result>
等節點。
MappedStatement
對應xxxMapper.xml映射檔案中的
<select>
、
<insert>
、
<update>
和
<delete>
節點。
SqlSource
對應xxxMapper.xml映射檔案中的sql語句,經過解析SqlSource包含的語句最終僅僅包含?占位符,可以直接送出給資料庫執行;
MapperRegistry
它是Mapper接口動态代理工廠類的注冊中心。在MyBatis中,通過MapperProxy實作InvocationHandler接口,通過MapperProxyFactory生成動态代理的執行個體對象;
MyBatis建造者類圖
Mybatis的整個初始化過程使用了建造者模式。建造者模式比較适合生成複雜對象,主要關注對象的執行個體化具體細節。