总体流程:
测试用例:断点在line26位置
1、调用DefaultSqlSessionFactory的openSession()方法
2、调用openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);方法
在此之前会调用configuration.getDefaultExecutorType()获取全局配置文件中的ExecutorType,此配置默认为SIMPLE。
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();
}
}
首先获取Environment对象信息:包括dataSource、transactionFactory
然后根据TransactionFactory获取Transaction对象,即事务管理器。
3、获取四大对象之Executor对象:
调用configuration.newExecutor(tx, execType);方法:
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;
}
先获取executorType的值:SIMPLE,再根据executorType的值创建Executor类型:BatchExecutor/ReuseExecutor/SimpleExecutor
如果全局配置文件配置了二级缓存:使用CachingExecutor包装executor对象。此时,在进行增删改查的时候,会在执行之前先进行缓存的处理。
配置拦截器的时候,调用interceptorChain.pluginAll(executor)方法再次包装executor对象:executor = (Executor) interceptorChain.pluginAll(executor);
最终得到的executor对象为:
4、返回DefaultSqlSession对象,里面包含了Executor和Configuration。
获取完Executor对象后,流程回到2,调用openSessionFromDataSource()方法,使用configuration, executor对象创建DefaultSqlSession对象。