SqlSession的创建过程

上一篇 << 下一篇 >>>sqlSession如何获得具体的Mapper接口信息


原理

从configuration中获得环境,取得事务工厂并创建事务,通过事务创建执行器,然后封装到DefaultSqlSession返回。执行器模式使用SimpleExecutor,由于默认开启了二级缓存,所以再用CachingExecutor对SimpleExecutor做了一次封装。

核心源码

// 从configuration中获得环境
Environment environment = this.configuration.getEnvironment();
// 取得事务工厂并创建事务
TransactionFactory transactionFactory = this.getTransactionFactoryFromEnvironment(environment);
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
//通过事务创建执行器
Executor executor = this.configuration.newExecutor(tx, execType);---》
// 然后封装到DefaultSqlSession返回
// SqlSession这个接口帮我们封装了CRUD的方法,便于我们操作,Mybatis默认最多能查到Integer的最大值21亿。
var8 = new DefaultSqlSession(this.configuration, executor, autoCommit);

if (this.cacheEnabled) {
executor = new CachingExecutor((Executor)executor);
}

执行器的类型与作用

CachingExecutor为二级缓存执行器,BaseExecutor为一级缓存执行器。
默认情况下使用缓存的CachingExecutor
SimpleExecutor: 默认的 Executor,每个 SQL 执行时都会创建新的 Statement
ResuseExecutor: 相同的 SQL 会复用 Statement
BatchExecutor: 用于批处理的 Executor
CachingExecutor: 可缓存数据的 Executor,用代理模式包装了其它类型的 Executor

Object 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);
}

为什么CachingExecutor要找SimpleExecutor创建缓存key?

答案是为了复用,实现缓存key代码复用。mybatis缓存控制:先查找二级缓存(需要自己配置),二级缓存没有的情况下,再去找一级缓存(默认都有)


推荐阅读:
<< << << << << << << << << <<

你可能感兴趣的:(SqlSession的创建过程)