一 MapperFactoryBean
1.1 MapperFactoryBean
- spring容器中管理的dao接口bean是MapperFactoryBean
- MapperFactoryBean.getObject()的實(shí)現(xiàn)是調(diào)用
this.getSqlSession()
獲取的DefaultSqlSession的方法getMapper(this.mapperInterface);
- DefaultSqlSession中調(diào)用的是mybatis配置的getMapper(type, this)`方法
- mybatis配置中調(diào)用的是mapperRegistry的
getMapper(type, sqlSession)
方法
1.2 MapperRegistry
- spring掃描dao接口包時(shí)酸休,添加接口對應(yīng)的代理工廠類,MapperRegistry中
Map<Class<?>/*dao接口*/, MapperProxyFactory<?>> knownMappers
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 {
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.
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
parser.parse();
loadCompleted = true;
} finally {
if (!loadCompleted) {
knownMappers.remove(type);
}
}
}
}
1.3 MapperProxy
- 獲取時(shí)使用工廠類新建實(shí)例
mapperProxyFactory.newInstance(sqlSession)
,即以MapperProxy為代理函數(shù)的代理類
Proxy.newProxyInstance(mapperInterface.getClassLoader(),
new Class[] { mapperInterface },
new MapperProxy<T>(sqlSession, mapperInterface, methodCache));
- MapperProxy使用MapperMethod代理底層不同dao接口,進(jìn)行接口參數(shù)轉(zhuǎn)換和返回值轉(zhuǎn)換获三,并調(diào)用sqlsession代理接口
1.4 MapperMethod
public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
this.command = new SqlCommand(config, mapperInterface, method);
this.method = new MethodSignature(config, method);
}
1.4.1 SqlCommand
- 函數(shù)對應(yīng)sql指令名為接口名.方法名
- 從mybatis配置中獲取映射文件解析的sql指令對應(yīng)的MappedStatement
- 存儲sql指令名稱和類型
name = ms.getId();
type = ms.getSqlCommandType();
1.4.2 MethodSignature
- 存儲sql方法的參數(shù)和返回值层坠,并提供轉(zhuǎn)換方法
二 SqlSession
2.1 SqlSessionTemplate
- SqlSession工廠代理退盯,線程局部變量保存奄喂,線程安全。支持事務(wù)sqlSession的線程內(nèi)共享绵脯。
- 代理DefaultSqlSession的接口
2.2 DefaultSqlSession
2.2.1 初始化
- 初始化或獲取線程共享事務(wù)
- 根據(jù)執(zhí)行器類型新建sql命令執(zhí)行器
- 實(shí)例化DefaultSqlSession
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
final Environment environment = configuration.getEnvironment();
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
final Executor executor = configuration.newExecutor(tx, execType);
return new DefaultSqlSession(configuration, executor, autoCommit);
} catch (Exception e) {
closeTransaction(tx); // may have fetched a connection so lets call close()
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
2.2.2 方法
- select*方法調(diào)用executor.query()
- insert佳励,update,delete調(diào)用executor.update()
- commit蛆挫,rollback赃承,flush調(diào)用executor的對應(yīng)函數(shù)
三 executor
3.1 初始化
- 根據(jù)類型創(chuàng)建executor,并增加執(zhí)行器插件代理璃吧。默認(rèn)是SIMPLE類型楣导。
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
executor = new SimpleExecutor(this, transaction);
}
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
3.2 SimpleExecutor
3.2.1 doUpdate處理流程
- 初始化RoutingStatementHandler,添加對應(yīng)的指令插件
-
Statement stmt = handler.prepare(connection);
Statement預(yù)處理
-
handler.parameterize(stmt);
參數(shù)設(shè)置
-
handler.update(stmt);
執(zhí)行更新
3.2.2 doQuery處理流程
- 初始化RoutingStatementHandler畜挨,添加對應(yīng)的指令插件
-
Statement stmt = handler.prepare(connection);
Statement預(yù)處理
-
handler.parameterize(stmt);
參數(shù)設(shè)置
-
handler.<E>query(stmt, resultHandler);;
執(zhí)行查詢筒繁,resultHandler進(jìn)行返回結(jié)果處理
3.3 ReuseExecutor
- doUpdate,doQuery處理流程與SimpleExecutor相同
- 區(qū)別是提供了
Map<String, Statement> statementMap
。以sql命令為key對Statement stmt
的緩存
-
doFlushStatements()
統(tǒng)一清除緩存巴元,關(guān)閉Statement
3.4 BatchExecutor
3.5 BaseExecutor
- 所有executor繼承自BaseExecutor
- update調(diào)用子類doUpdate之前毡咏,先清除本地緩存
3.5.1 query
- 查詢時(shí)執(zhí)行一級緩存,SqlSession內(nèi)共享逮刨,對事務(wù)性查詢是線程內(nèi)共享SqlSession呕缭,也就是共享一級緩存數(shù)據(jù)堵泽。
- 先判斷flushCache配置,為true恢总,則先清空緩存迎罗,默認(rèn)為false
- 查詢緩存以key存儲,
CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql)
- 存在緩存,則不再執(zhí)行sql查詢片仿。緩存參數(shù)
localOutputParameterCache
轉(zhuǎn)換后返回handleLocallyCachedOutputParameters()
-
deferredLoads
延遲加載處理
-
configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT
語句級范圍則請求完成后清除緩存纹安,session范圍緩存則可用。
3.6 CachingExecutor
- SqlSession存儲的執(zhí)行器實(shí)際是CachingExecutor砂豌,內(nèi)部代理了SimpleExecutor.
- CachingExecutor實(shí)現(xiàn)了mybatis的二級緩存功能厢岂,緩存數(shù)據(jù)存儲在MappedStatement中,
Cache cache = ms.getCache();
- MappedStatement是多個(gè)SqlSession共享的阳距,即二級緩存是共享實(shí)用的塔粒。
- 查詢時(shí),若配置使用二級緩存則先取緩存中數(shù)據(jù)
四 插件
- 在mybatis配置中使用
InterceptorChain interceptorChain
保存所有插件配置
4.1 InterceptorChain
- 使用
List<Interceptor> interceptors
存儲所有插件
- 調(diào)用插件方法
target = interceptor.plugin(target);
筐摘,對目標(biāo)類創(chuàng)建插件代理卒茬,一般內(nèi)部實(shí)現(xiàn)使用org.apache.ibatis.plugin.Plugin
創(chuàng)建代理。
4.2 Plugin
public static Object wrap(Object target, Interceptor interceptor) {
Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
Class<?> type = target.getClass();
Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
if (interfaces.length > 0) {
return Proxy.newProxyInstance(
type.getClassLoader(),
interfaces,
new Plugin(target, interceptor, signatureMap));
}
return target;
}
- 攔截方法內(nèi)蓄拣,則調(diào)用插件的
intercept
方法扬虚,執(zhí)行插件處理。
Set<Method> methods = signatureMap.get(method.getDeclaringClass());
if (methods != null && methods.contains(method)) {
return interceptor.intercept(new Invocation(target, method, args));
}
- 不在攔截方法內(nèi)球恤,則直接調(diào)用目標(biāo)方法。
return method.invoke(target, args);
4.3 插件類型
- 插件分為Executor執(zhí)行器插件荸镊,ParameterHandler參數(shù)處理插件咽斧,ResultSetHandler結(jié)果處理插件,StatementHandler預(yù)處理插件躬存。
-
interceptor.plugin(target)
創(chuàng)建插件代理時(shí)张惹,需要判斷target
是否是期望的插件目標(biāo)點(diǎn)
- ParameterHandler參數(shù)處理插件
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
return parameterHandler;
}
- ResultSetHandler結(jié)果處理插件
ResultHandler resultHandler, BoundSql boundSql) {
ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
return resultSetHandler;
}
- StatementHandler預(yù)處理插件
public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
return statementHandler;
}
- Executor執(zhí)行器插件,在根據(jù)執(zhí)行器類型
newExecutor
新建執(zhí)行器時(shí)岭洲,創(chuàng)建executor = (Executor) interceptorChain.pluginAll(executor);