MyBatis(9)——运行原理-获取SqlSession对象

本文详细解析了MyBatis的执行流程,从调用openSession()开始,深入介绍了如何获取Environment、Transaction、Executor对象,并最终创建DefaultSqlSession。特别关注了Executor类型的创建过程及二级缓存的使用。

总体流程:

测试用例:断点在line26位置

1、调用DefaultSqlSessionFactory的openSession()方法

2、调用openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);方法

在此之前会调用configuration.getDefaultExecutorType()获取全局配置文件中的ExecutorType,此配置默认为SIMPLE。

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

首先获取Environment对象信息:包括dataSource、transactionFactory

然后根据TransactionFactory获取Transaction对象,即事务管理器。

3、获取四大对象之Executor对象:

调用configuration.newExecutor(tx, execType);方法:

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

先获取executorType的值:SIMPLE,再根据executorType的值创建Executor类型:BatchExecutor/ReuseExecutor/SimpleExecutor

如果全局配置文件配置了二级缓存:使用CachingExecutor包装executor对象。此时,在进行增删改查的时候,会在执行之前先进行缓存的处理。

配置拦截器的时候,调用interceptorChain.pluginAll(executor)方法再次包装executor对象:executor = (Executor) interceptorChain.pluginAll(executor);

最终得到的executor对象为:

4、返回DefaultSqlSession对象,里面包含了Executor和Configuration。

获取完Executor对象后,流程回到2,调用openSessionFromDataSource()方法,使用configuration, executor对象创建DefaultSqlSession对象。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值