文章目录
一、openSession()作用概括
- 创建事务
- 创建Excutor
- 把创建好得事务和Excutor交给DefaultSqlSession
- 封装了select | insert | update | delete方法
二、openSession()源码分析
1、用法中
用法中我们通过sqlSessionFactory.build()方法创建好sqlSessionFactory然后通过
SqlSession sqlSession = sqlSessionFactory.openSession();
获取我们得sqlSession那么我们接下来去看源码
2、openSession()
@Override
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
可以看到openSession中调用了openSessionFromDataSource方法 我们继续追踪源码
3、openSessionFromDataSource()
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);
//返回DefaultSqlSession
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();
}
}
4、获取Executor 执行器
1.执行器类型
- SimpleExecutor:默认的Executor,每个SQL执行时候都会创建新的Statement
- ReuseExecutor:相同的SQL会重复使用Statement
- BatchExecutor:用于批处理的Executor
- CachingExecutor:可缓存数据的Executor,用代理模式包装了其他类型的Executor
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);
}
//默认是true 默认先创建简单的Executor 然后再创建CachingExecutor
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
executor = (Executor) interceptorChain.pluginAll(executor);
//最后把创建好的执行器返回
return executor;
}