流程图
- DefaultSqlSessionFactory调用opensseion方法
- opensession方法下,调用openSessionFromDataSource方法
- openSessionFromDataSource方法下获取configuration信息,并创建事务,调用newExecutor方法,生成Executor,并返回
- 拦截器类对Executor进行加强后返回Executor
- 返回DefaultSqlSession给DefaultSqlSessionFactory
剖析源码
1.DefaultSqlSessionFactory调用openSession方法
sqlSession = sqlSessionFactory.openSession();
2.openSession方法下调用openSessionFromDataSource方法
public SqlSession openSession() {
//调用此方法会返回SqlSession
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
3.openSessionFromDataSource下获取配置信息,生成事务和Executor并返回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);
//生成Executor
final Executor executor = configuration.newExecutor(tx, execType);
//传入配置信息和Executor,创建SqlSession
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();
}
}
5.Executor
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
//判断Executor类型
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
//默认Execuotr类型为SIMPLE
executor = new SimpleExecutor(this, transaction);
}
//如果开启了二级缓存,则生成CachingExecutor
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
//调用拦截器链加强Executor对象,插件在此发挥作用
executor = (Executor) interceptorChain.pluginAll(executor);
//返回Executor
return executor;
}
小结
调用DefaultSqlSessionFactory下的openSession方法可以返回SqlSession。在此之前,需要传入Configuration,创建Executor作为参数传入,生成Executor的条件需要事务管理和Executor类型。完成信息的配置后,返回SqlSession给调用者。