@
目錄- 前言
- 正文
- 配置決議
- 1. cacheRefElement/cacheElement
- 2. resultMapElements
- 3. sqlElement
- 4. buildStatementFromContext
- 配置決議
- 總結
前言
上一篇分析了Mybatis的基礎組件,Mybatis的運行呼叫就是建立在這些基礎組件之上的,那它的執行原理又是怎樣的呢?在往下之前不妨先思考下如果是你會怎么實作,
正文
熟悉Mybatis的都知道,在使用Mybatis時需要配置一個mybatis-config.xml檔案,另外還需要定義Mapper介面和Mapper.xml檔案,在config檔案中引入或掃描對應的包才能被加載決議(現在由于大多是SpringBoot工程,基本上都不會配置config檔案,而是通過注解進行掃描就行了,但本質上的實作和xml配置沒有太大區別,所以本篇仍以xml配置方式進行分析,),所以Mybatis的第一個階段必然是要去加載并決議組態檔,這個階段在專案啟動時就應該完成,后面直接呼叫即可,加載完成之后,自然就是等待呼叫,但是我們在專案中只會定義Mapper介面和Mapper.xml檔案,那具體的實作類在哪呢?Mybatis是通過動態代理實作的,所以第二個階段應該是生成Mapper介面的代理實作類,通過呼叫代理類,最侄訓生成對應的sql訪問資料庫并獲取結果,所以最后一個階段就是SQL決議(引數映射、SQL映射、結果映射),本文主要分析配置決議階段,
配置決議
Mybatis可以通過下面的方式決議組態檔:
final String resource = "org/apache/ibatis/builder/MapperConfig.xml";
final Reader reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
所以入口就是build方法(從名字可以看出使用了建造者模式,它和工廠模式一樣,也是解用于創建物件的一種模式,不過與工廠模式不一樣的是,前者需要我們自己參與構建的細節,而后者則不需要):
public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
try {
//讀取組態檔
XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
return build(parser.parse());//決議組態檔得到configuration物件,并回傳SqlSessionFactory
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
reader.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
這里先是創建了一個XMLConfigBuilder物件,這個物件就是用來加載決議config檔案的,先看看它的構造方法中做了些什么事情:
public XMLConfigBuilder(Reader reader, String environment, Properties props) {
this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);
}
private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {
super(new Configuration());
ErrorContext.instance().resource("SQL Mapper Configuration");
this.configuration.setVariables(props);
this.parsed = false;
this.environment = environment;
this.parser = parser;
}
需要注意的是這里創建了一個Configuration物件,他就是Mybatis的核心CPU,保存了所有的配置資訊,在后面的執行階段所需要的資訊都是從這個類取的,因為這個類比較大,這里就不貼詳細代碼了,讀者請務必閱讀原始碼熟悉該類,因為這個類物件保存了所有的配置資訊,那么必然這個類是全域單例的,事實上這個物件的創建也只有這里一個入口,保證了全域唯一,
在該類的構造方法中,首先就注冊了核心組件的別名和對應的類映射關系:
public Configuration() {
typeAliasRegistry.registerAlias("JDBC", JdbcTransactionFactory.class);
typeAliasRegistry.registerAlias("MANAGED", ManagedTransactionFactory.class);
typeAliasRegistry.registerAlias("JNDI", JndiDataSourceFactory.class);
typeAliasRegistry.registerAlias("POOLED", PooledDataSourceFactory.class);
typeAliasRegistry.registerAlias("UNPOOLED", UnpooledDataSourceFactory.class);
......省略
languageRegistry.setDefaultDriverClass(XMLLanguageDriver.class);
languageRegistry.register(RawLanguageDriver.class);
}
而注冊類在實體化時同樣也注冊了一些基礎型別的別名映射:
public TypeAliasRegistry() {
registerAlias("string", String.class);
registerAlias("byte", Byte.class);
registerAlias("long", Long.class);
registerAlias("short", Short.class);
registerAlias("int", Integer.class);
registerAlias("integer", Integer.class);
registerAlias("double", Double.class);
registerAlias("float", Float.class);
registerAlias("boolean", Boolean.class);
......省略
registerAlias("ResultSet", ResultSet.class);
}
看到這相信你就知道parameterType和resultType屬性的簡寫是怎么實作的了,回到主流程,進入到parser.parse方法中:
public Configuration parse() {
if (parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
parsed = true;
parseConfiguration(parser.evalNode("/configuration"));
return configuration;
}
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);
//決議<typeAliases>節點
typeAliasesElement(root.evalNode("typeAliases"));
//決議<plugins>節點
pluginElement(root.evalNode("plugins"));
//決議<objectFactory>節點
objectFactoryElement(root.evalNode("objectFactory"));
//決議<objectWrapperFactory>節點
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
//決議<reflectorFactory>節點
reflectorFactoryElement(root.evalNode("reflectorFactory"));
settingsElement(settings);//將settings填充到configuration
// read it after objectFactory and objectWrapperFactory issue #631
//決議<environments>節點
environmentsElement(root.evalNode("environments"));
//決議<databaseIdProvider>節點
databaseIdProviderElement(root.evalNode("databaseIdProvider"));
//決議<typeHandlers>節點
typeHandlerElement(root.evalNode("typeHandlers"));
//決議<mappers>節點
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
這個方法就是去決議組態檔中的各個節點,并將其封裝到Configuration物件中去,前面的節點決議沒啥好說的,自己看一下就明白了,重點看一下最后一個對mapper節點的決議,這個就是加載我們的Mapper.xml檔案:
<mappers>
<mapper resource="org/apache/ibatis/builder/AuthorMapper.xml"/>
<mapper resource="org/apache/ibatis/builder/BlogMapper.xml"/>
<mapper resource="org/apache/ibatis/builder/CachedAuthorMapper.xml"/>
<mapper resource="org/apache/ibatis/builder/PostMapper.xml"/>
<mapper resource="org/apache/ibatis/builder/NestedBlogMapper.xml"/>
</mappers>
private void mapperElement(XNode parent) throws Exception {
if (parent != null) {
for (XNode child : parent.getChildren()) {//處理mapper子節點
if ("package".equals(child.getName())) {//package子節點
String mapperPackage = child.getStringAttribute("name");
configuration.addMappers(mapperPackage);
} else {//獲取<mapper>節點的resource、url或mClass屬性這三個屬性互斥
String resource = child.getStringAttribute("resource");
String url = child.getStringAttribute("url");
String mapperClass = child.getStringAttribute("class");
if (resource != null && url == null && mapperClass == null) {//如果resource不為空
ErrorContext.instance().resource(resource);
InputStream inputStream = Resources.getResourceAsStream(resource);//加載mapper檔案
//實體化XMLMapperBuilder決議mapper映射檔案
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
mapperParser.parse();
} else if (resource == null && url != null && mapperClass == null) {//如果url不為空
ErrorContext.instance().resource(url);
InputStream inputStream = Resources.getUrlAsStream(url);//加載mapper檔案
//實體化XMLMapperBuilder決議mapper映射檔案
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
mapperParser.parse();
} else if (resource == null && url == null && mapperClass != null) {//如果class不為空
Class<?> mapperInterface = Resources.classForName(mapperClass);//加載class物件
configuration.addMapper(mapperInterface);//向代理中心注冊mapper
} else {
throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
}
}
}
}
}
從上面的代碼中我們可以看到這里有兩種配置方式,一種是配置package子節點,即掃描并批量加載指定的包中的檔案;另一種則是使用mapper子節點引入單個檔案,而mapper節點又可以配置三種屬性:resource、url、class,而決議XML的核心類是XMLMapperBuilder,進入parse方法:
public void parse() {
//判斷是否已經加載該組態檔
if (!configuration.isResourceLoaded(resource)) {
configurationElement(parser.evalNode("/mapper"));//處理mapper節點
configuration.addLoadedResource(resource);//將mapper檔案添加到configuration.loadedResources中
bindMapperForNamespace();//注冊mapper介面
}
//處理決議失敗的ResultMap節點
parsePendingResultMaps();
//處理決議失敗的CacheRef節點
parsePendingCacheRefs();
//處理決議失敗的Sql陳述句節點
parsePendingStatements();
}
private void configurationElement(XNode context) {
try {
//獲取mapper節點的namespace屬性
String namespace = context.getStringAttribute("namespace");
if (namespace == null || namespace.equals("")) {
throw new BuilderException("Mapper's namespace cannot be empty");
}
//設定builderAssistant的namespace屬性
builderAssistant.setCurrentNamespace(namespace);
//決議cache-ref節點
cacheRefElement(context.evalNode("cache-ref"));
//重點分析 :決議cache節點----------------1-------------------
cacheElement(context.evalNode("cache"));
//決議parameterMap節點(已廢棄)
parameterMapElement(context.evalNodes("/mapper/parameterMap"));
//重點分析 :決議resultMap節點(基于資料結果去理解)----------------2-------------------
resultMapElements(context.evalNodes("/mapper/resultMap"));
//決議sql節點
sqlElement(context.evalNodes("/mapper/sql"));
//重點分析 :決議select、insert、update、delete節點 ----------------3-------------------
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);
}
}
核心的處理邏輯又是通過configurationElement實作的,接下來挨個分析幾個重要節點決議程序,
1. cacheRefElement/cacheElement
這兩個節點都是決議二級快取配置的,前者是參考其它namespace的二級快取,后者則是直接開啟當前namespace的二級快取,所以重點看后者:
private void cacheElement(XNode context) throws Exception {
if (context != null) {
//獲取cache節點的type屬性,默認為PERPETUAL
String type = context.getStringAttribute("type", "PERPETUAL");
//找到type對應的cache介面的實作
Class<? extends Cache> typeClass = typeAliasRegistry.resolveAlias(type);
//讀取eviction屬性,既快取的淘汰策略,默認LRU
String eviction = context.getStringAttribute("eviction", "LRU");
//根據eviction屬性,找到裝飾器
Class<? extends Cache> evictionClass = typeAliasRegistry.resolveAlias(eviction);
//讀取flushInterval屬性,既快取的重繪周期
Long flushInterval = context.getLongAttribute("flushInterval");
//讀取size屬性,既快取的容量大小
Integer size = context.getIntAttribute("size");
//讀取readOnly屬性,既快取的是否只讀
boolean readWrite = !context.getBooleanAttribute("readOnly", false);
//讀取blocking屬性,既快取的是否阻塞
boolean blocking = context.getBooleanAttribute("blocking", false);
Properties props = context.getChildrenAsProperties();
//通過builderAssistant創建快取物件,并添加至configuration
builderAssistant.useNewCache(typeClass, evictionClass, flushInterval, size, readWrite, blocking, props);
}
}
public Cache useNewCache(Class<? extends Cache> typeClass,
Class<? extends Cache> evictionClass,
Long flushInterval,
Integer size,
boolean readWrite,
boolean blocking,
Properties props) {
//經典的建造起模式,創建一個cache物件
Cache cache = new CacheBuilder(currentNamespace)
.implementation(valueOrDefault(typeClass, PerpetualCache.class))
.addDecorator(valueOrDefault(evictionClass, LruCache.class))
.clearInterval(flushInterval)
.size(size)
.readWrite(readWrite)
.blocking(blocking)
.properties(props)
.build();
//將快取添加至configuration,注意二級快取以命名空間為單位進行劃分
configuration.addCache(cache);
currentCache = cache;
return cache;
}
public void addCache(Cache cache) {
caches.put(cache.getId(), cache);
}
從這里我們可以看到默認創建了PerpetualCache物件,這個是快取的基本實作類,然后根據配置給快取加上裝飾器,默認會裝飾LRU,配置決議完成后,才會通過MapperBuilderAssistant類真正創建快取物件并添加到Configuration物件中,為什么這里要通過MapperBuilderAssistant物件創建快取物件呢?從名字可以看出它是XMLMapperBuilder的協助者,因為XML的決議和配置物件的裝填是非常繁瑣的一個程序,如果全部由一個類來完成,會非常的臃腫難看,并且耦合性較高,所以這里又雇傭了一個“協助者”,
2. resultMapElements
private void resultMapElements(List<XNode> list) throws Exception {
//遍歷所有的resultmap節點
for (XNode resultMapNode : list) {
try {
//決議具體某一個resultMap節點
resultMapElement(resultMapNode);
} catch (IncompleteElementException e) {
// ignore, it will be retried
}
}
}
private ResultMap resultMapElement(XNode resultMapNode, List<ResultMapping> additionalResultMappings) throws Exception {
ErrorContext.instance().activity("processing " + resultMapNode.getValueBasedIdentifier());
//獲取resultmap節點的id屬性
String id = resultMapNode.getStringAttribute("id",
resultMapNode.getValueBasedIdentifier());
//獲取resultmap節點的type屬性
String type = resultMapNode.getStringAttribute("type",
resultMapNode.getStringAttribute("ofType",
resultMapNode.getStringAttribute("resultType",
resultMapNode.getStringAttribute("javaType"))));
//獲取resultmap節點的extends屬性,描述繼承關系
String extend = resultMapNode.getStringAttribute("extends");
//獲取resultmap節點的autoMapping屬性,是否開啟自動映射
Boolean autoMapping = resultMapNode.getBooleanAttribute("autoMapping");
//從別名注冊中心獲取entity的class物件
Class<?> typeClass = resolveClass(type);
Discriminator discriminator = null;
//記錄子節點中的映射結果集合
List<ResultMapping> resultMappings = new ArrayList<>();
resultMappings.addAll(additionalResultMappings);
//從xml檔案中獲取當前resultmap中的所有子節點,并開始遍歷
List<XNode> resultChildren = resultMapNode.getChildren();
for (XNode resultChild : resultChildren) {
if ("constructor".equals(resultChild.getName())) {//處理<constructor>節點
processConstructorElement(resultChild, typeClass, resultMappings);
} else if ("discriminator".equals(resultChild.getName())) {//處理<discriminator>節點
discriminator = processDiscriminatorElement(resultChild, typeClass, resultMappings);
} else {//處理<id> <result> <association> <collection>節點
List<ResultFlag> flags = new ArrayList<>();
if ("id".equals(resultChild.getName())) {
flags.add(ResultFlag.ID);//如果是id節點,向flags中添加元素
}
//創建ResultMapping物件并加入resultMappings集合中
resultMappings.add(buildResultMappingFromContext(resultChild, typeClass, flags));
}
}
//實體化resultMap決議器
ResultMapResolver resultMapResolver = new ResultMapResolver(builderAssistant, id, typeClass, extend, discriminator, resultMappings, autoMapping);
try {
//通過resultMap決議器實體化resultMap并將其注冊到configuration物件
return resultMapResolver.resolve();
} catch (IncompleteElementException e) {
configuration.addIncompleteResultMap(resultMapResolver);
throw e;
}
}
這個方法同樣先是決議節點的屬性,然后通過buildResultMappingFromContext方法創建ResultMapping物件并封裝到ResultMapResolver中去,最后還是通過MapperBuilderAssistant實體化ResultMap物件并添加到Configuration的resultMaps屬性中:
public ResultMap addResultMap(
String id,
Class<?> type,
String extend,
Discriminator discriminator,
List<ResultMapping> resultMappings,
Boolean autoMapping) {
//完善id,id的完整格式是"namespace.id"
id = applyCurrentNamespace(id, false);
//獲得父類resultMap的完整id
extend = applyCurrentNamespace(extend, true);
//針對extend屬性的處理
if (extend != null) {
if (!configuration.hasResultMap(extend)) {
throw new IncompleteElementException("Could not find a parent resultmap with id '" + extend + "'");
}
ResultMap resultMap = configuration.getResultMap(extend);
List<ResultMapping> extendedResultMappings = new ArrayList<>(resultMap.getResultMappings());
extendedResultMappings.removeAll(resultMappings);
// Remove parent constructor if this resultMap declares a constructor.
boolean declaresConstructor = false;
for (ResultMapping resultMapping : resultMappings) {
if (resultMapping.getFlags().contains(ResultFlag.CONSTRUCTOR)) {
declaresConstructor = true;
break;
}
}
if (declaresConstructor) {
Iterator<ResultMapping> extendedResultMappingsIter = extendedResultMappings.iterator();
while (extendedResultMappingsIter.hasNext()) {
if (extendedResultMappingsIter.next().getFlags().contains(ResultFlag.CONSTRUCTOR)) {
extendedResultMappingsIter.remove();
}
}
}
//添加需要被繼承下來的resultMapping物件結合
resultMappings.addAll(extendedResultMappings);
}
//通過建造者模式實體化resultMap,并注冊到configuration.resultMaps中
ResultMap resultMap = new ResultMap.Builder(configuration, id, type, resultMappings, autoMapping)
.discriminator(discriminator)
.build();
configuration.addResultMap(resultMap);
return resultMap;
}
3. sqlElement
決議SQL節點,只是將其快取到XMLMapperBuilder的sqlFragments屬性中,
4. buildStatementFromContext
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) {
//創建XMLStatementBuilder 專門用于決議sql陳述句節點
final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);
try {
//決議sql陳述句節點
statementParser.parseStatementNode();
} catch (IncompleteElementException e) {
configuration.addIncompleteStatement(statementParser);
}
}
}
這個方法是重點,通過XMLStatementBuilder物件決議select、update、insert、delete節點:
public void parseStatementNode() {
//獲取sql節點的id
String id = context.getStringAttribute("id");
String databaseId = context.getStringAttribute("databaseId");
if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
return;
}
/*獲取sql節點的各種屬性*/
Integer fetchSize = context.getIntAttribute("fetchSize");
Integer timeout = context.getIntAttribute("timeout");
String parameterMap = context.getStringAttribute("parameterMap");
String parameterType = context.getStringAttribute("parameterType");
Class<?> parameterTypeClass = resolveClass(parameterType);
String resultMap = context.getStringAttribute("resultMap");
String resultType = context.getStringAttribute("resultType");
String lang = context.getStringAttribute("lang");
LanguageDriver langDriver = getLanguageDriver(lang);
Class<?> resultTypeClass = resolveClass(resultType);
String resultSetType = context.getStringAttribute("resultSetType");
StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString()));
ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType);
//根據sql節點的名稱獲取SqlCommandType(INSERT, UPDATE, DELETE, SELECT)
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
//在決議sql陳述句之前先決議<include>節點
XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);
includeParser.applyIncludes(context.getNode());
// Parse selectKey after includes and remove them.
//在決議sql陳述句之前,處理<selectKey>子節點,并在xml節點中洗掉
processSelectKeyNodes(id, parameterTypeClass, langDriver);
// Parse the SQL (pre: <selectKey> and <include> were parsed and removed)
//決議sql陳述句是決議mapper.xml的核心,實體化sqlSource,使用sqlSource封裝sql陳述句
SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
String resultSets = context.getStringAttribute("resultSets");//獲取resultSets屬性
String keyProperty = context.getStringAttribute("keyProperty");//獲取主鍵資訊keyProperty
String keyColumn = context.getStringAttribute("keyColumn");///獲取主鍵資訊keyColumn
//根據<selectKey>獲取對應的SelectKeyGenerator的id
KeyGenerator keyGenerator;
String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX;
keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true);
//獲取keyGenerator物件,如果是insert型別的sql陳述句,會使用KeyGenerator介面獲取資料庫生產的id;
if (configuration.hasKeyGenerator(keyStatementId)) {
keyGenerator = configuration.getKeyGenerator(keyStatementId);
} else {
keyGenerator = context.getBooleanAttribute("useGeneratedKeys",
configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))
? Jdbc3KeyGenerator.INSTANCE : NoKeyGenerator.INSTANCE;
}
//通過builderAssistant實體化MappedStatement,并注冊至configuration物件
builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
resultSetTypeEnum, flushCache, useCache, resultOrdered,
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
}
public MappedStatement addMappedStatement(
String id,
SqlSource sqlSource,
StatementType statementType,
SqlCommandType sqlCommandType,
Integer fetchSize,
Integer timeout,
String parameterMap,
Class<?> parameterType,
String resultMap,
Class<?> resultType,
ResultSetType resultSetType,
boolean flushCache,
boolean useCache,
boolean resultOrdered,
KeyGenerator keyGenerator,
String keyProperty,
String keyColumn,
String databaseId,
LanguageDriver lang,
String resultSets) {
if (unresolvedCacheRef) {
throw new IncompleteElementException("Cache-ref not yet resolved");
}
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;
}
同樣的,最后根據sql陳述句和屬性實體化MappedStatement物件,并添加到Configuration物件的mappedStatements屬性中,
回到XMLMapperBuilder.parse方法中,在決議完xml之后又呼叫了bindMapperForNamespace方法:
private void bindMapperForNamespace() {
//獲取命名空間
String namespace = builderAssistant.getCurrentNamespace();
if (namespace != null) {
Class<?> boundType = null;
try {
//通過命名空間獲取mapper介面的class物件
boundType = Resources.classForName(namespace);
} catch (ClassNotFoundException e) {
//ignore, bound type is not required
}
if (boundType != null) {
if (!configuration.hasMapper(boundType)) {//是否已經注冊過該mapper介面?
// Spring may not know the real resource name so we set a flag
// to prevent loading again this resource from the mapper interface
// look at MapperAnnotationBuilder#loadXmlResource
//將命名空間添加至configuration.loadedResource集合中
configuration.addLoadedResource("namespace:" + namespace);
//將mapper介面添加到mapper注冊中心
configuration.addMapper(boundType);
}
}
}
}
這個方法中首先通過namespace拿到xml對應的Mapper介面型別,然后委托給Configuration類中的mapperRegistry注冊動態的代理的工廠MapperProxyFactory:
public <T> void addMapper(Class<T> type) {
if (type.isInterface()) {
if (hasMapper(type)) {
throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
}
boolean loadCompleted = false;
try {
//實體化Mapper介面的代理工程類,并將資訊添加至knownMappers
knownMappers.put(type, new MapperProxyFactory<T>(type));
// It's important that the type is added before the parser is run
// otherwise the binding may automatically be attempted by the
// mapper parser. If the type is already known, it won't try.
//決議介面上的注解資訊,并添加至configuration物件
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
parser.parse();
loadCompleted = true;
} finally {
if (!loadCompleted) {
knownMappers.remove(type);
}
}
}
}
這個就是創建Mapper介面的動態代理物件的工廠類,所以Mapper的代理物件實際上并不是在啟動的時候就創建好了,而是在方法呼叫時才會創建,為什么會這么設計呢?因為代理物件和SqlSession是一一對應的,而我們每一次呼叫Mapper的方法都是創建一個新的SqlSession,所以這里只是快取了代理工廠物件,
代理工廠注冊之后還通過MapperAnnotationBuilder類提供了對注解方式的支持,這里就不闡述了,結果就是將注解的值添加到Configuration中去,
總結
決議組態檔的流程雖然比較長,但邏輯一點都不復雜,主要就是獲取xml配置的屬性值,實體化不同的配置物件,并將這些配置都丟到Configuration物件中去,我們只需要重點關注哪些物件被注冊到了Configuration中去,最后根據Configuration物件實體化DefaultSqlSessionFactory物件并回傳,而DefaultSqlSessionFactory就是用來創建SqlSession物件的,這個物件就是上一篇架構圖中的介面層,它提供了所有訪問資料庫的操作并屏蔽了底層復雜實作細節,具體的實作原理將在下一篇進行分析,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/149780.html
標籤:Java
