看下执行下面这行代码的时候,都发生了什么
SqlSession sqlSession = sqlSessionFactory.openSession();
第一步:org.apache.ibatis.session.defaults.DefaultSqlSessionFactory#openSession()
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
第二步:org.apache.ibatis.session.defaults.DefaultSqlSessionFactory#openSessionFromDataSource
这块代码是根据配置的Environment创建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);
//创建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();
}
}
看下DefaultSqlSession的构造函数,DefaultSqlSession有一个Executor的属性。
public DefaultSqlSession(Configuration configuration, Executor executor, boolean autoCommit) {
this.configuration = configuration;
this.executor = executor;
this.dirty = false;
this.autoCommit = autoCommit;
}
接着就看下Executor的创建过程吧
org.apache.ibatis.session.Configuration#newExecutor(Transaction, ExecutorType)
这块代码有两点
一、根据ExecutorType创建不同的类型的Executor
也不难看出,Executor一共有三种类型
- BatchExecutor
- ReuseExecutor
- SimpleExecutor(默认)
还有就是,这三种Executor都可以再次封装为CachingExecutor
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;
}
二、加载插件 executor = (Executor) interceptorChain.pluginAll(executor);
org.apache.ibatis.plugin.InterceptorChain#pluginAll
public Object pluginAll(Object target) {
//遍历所有的插件,执行插件的plugin方法
for (Interceptor interceptor : interceptors) {
target = interceptor.plugin(target);
}
return target;
}