详细步骤
在openSession()处加上断点并执行—>DefaultSqlSessionFactory类的openSession()方法
@Override
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
进入openSessionFromDataSource,里面包含数据源和事务以及创建了四大对象的executor
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();
}
}
executor 非常重要,进入configuration.newExecutor(tx, execType);看executor 创建过程,在这里会根据defaultExecutorType 类型创建不同的executor 【默认是simple,详细见mybatis官方文档】,如果开启了二级缓存,
会创建CachingExecutor。
最后执行interceptorChain.pluginAll(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);
}
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
最后加到DefaultSqlSessionFactory类创建new DefaultSqlSession(configuration, executor, autoCommit);并返回。