本文共 3048 字,大约阅读时间需要 10 分钟。
openSession()openSessionFromDataSource()txnewExecutor()Executor在全局配置中的类型,创建出SimpleExecutor/ReuseExecutor/BatchExecutorCachingExecutor(executor)executor并返回DefaultSqlSession,包含Configuration和ExecutorDefaultSqlSessionopenSession()SqlSession openSession = sqlSessionFactory.openSession();
openSessionFromDataSource()从configuration中拿到默认的Executor类型。Executor类型的类型有三种:SIMPLE/REUSE/BATCH。
@Override public SqlSession openSession() { return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false); } txprivate 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(); } } newExecutor()传入的参数为事务管理器和Executor的类型,根据传入的类型来创建Executor,Executor是一个接口,是用来增删改查的。
final Executor executor = configuration.newExecutor(tx, execType);
Executor在全局配置中的类型,创建出SimpleExecutor/ReuseExecutor/BatchExecutorpublic 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); } //看全局配置中是否配置了二级缓存,如果有用CachingExecutor包装 if (cacheEnabled) { executor = new CachingExecutor(executor); } //使用拦截器包装executor executor = (Executor) interceptorChain.pluginAll(executor); return executor; } CachingExecutor(executor)对二级缓存的具体操作:
public CachingExecutor(Executor delegate) { this.delegate = delegate; delegate.setExecutorWrapper(this); } executor并返回pluginAll具体实现:拿到所有的拦截器,调用每一个拦截器的plugin方法。
public Object pluginAll(Object target) { for (Interceptor interceptor : interceptors) { target = interceptor.plugin(target); } return target; } DefaultSqlSession,包含Configuration和Executor
DefaultSqlSession总结:
DefaultSqlSession是sqlSession的实现类,里面包含了Executor和Configuration,Executor在这一步会被创建。 转载地址:http://mpwc.baihongyu.com/