MyBatis运行原理(二)SqlSession对象创建过程分析
PS:這篇博文承接上一篇:
MyBatis運(yùn)行原理(一)SqlSessionFactory對象創(chuàng)建過程分析
在上一篇博文中分析了SqlSessionFactory對象創(chuàng)建的過程,有了SqlSessionFactory對象工廠就可以創(chuàng)建SqlSession了,下面就來具體分析一下SqlSession對象創(chuàng)建的過程。
一、SqlSession對象創(chuàng)建過程分析
入口程序:
private SqlSessionFactory getSqlSessionFactory() throws IOException {String resource = "mybatis-config.xml";InputStream is = Resources.getResourceAsStream(resource);return new SqlSessionFactoryBuilder().build(is);}@Testpublic void testMyBatis3Simple() throws IOException {SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();// 將斷點(diǎn)打在下面代碼的前面SqlSession sqlSession = sqlSessionFactory.openSession();}1.首先會跳到DefaultSqlSessionFactory類中的openSession()方法中。
// ====== DefaultSqlSessionFactory 類中的方法 ======@Overridepublic SqlSession openSession() {return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);}在上面這個方法中調(diào)用了另一個方法:
openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit),這個方法做了些什么呢?下面我們就來追蹤一下。
2.configuration.newExecutor(tx, execType)創(chuàng)建過程如下:
// ====== Configuration 類中的方法 ======public Executor newExecutor(Transaction transaction, ExecutorType executorType) {executorType = executorType == null ? defaultExecutorType : executorType;executorType = executorType == null ? ExecutorType.SIMPLE : executorType;Executor executor;/*** 根據(jù)executorType 類型創(chuàng)建對應(yīng)的Executor * BatchExecutor:批量執(zhí)行器* ReuseExecutor:會執(zhí)行預(yù)處理的執(zhí)行器* SimpleExecutor:簡單的執(zhí)行器*/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 來包裝executor,* 在查詢之前都會先查詢緩存中是否有對應(yīng)的數(shù)據(jù)* 包裝的過程使用了裝飾者模式,裝飾者模式可參考博文:* http://blog.csdn.net/codejas/article/details/79112824*/if (cacheEnabled) {executor = new CachingExecutor(executor);// 最后使用每個攔截器重新包裝executor 并返回executor = (Executor) interceptorChain.pluginAll(executor);// executor 對象創(chuàng)建完成并返回return executor;}3.Executor 對象創(chuàng)建完成后,會接著執(zhí)行
openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit)方法。
到這里會接著向上一步返回,SqlSession對象創(chuàng)建的過程也就結(jié)束了。
調(diào)用過程時序圖:
二、總結(jié)
這篇博文對sqlSessionFactory創(chuàng)建SqlSession對象的過程進(jìn)行了源碼分析,最后返回的SqlSession中包含有兩個重要的對象,分別是configuration與executor。configuration對象在創(chuàng)建SqlSessionFactory的時候就已經(jīng)被創(chuàng)建出來了,用來保存全局配置文件與SQL 映射文件中的信息,executor是一個執(zhí)行器對象。如果你想了解更多的細(xì)節(jié),可以自己查看源碼,希望這篇博文能夠?yàn)槟闾峁椭?/p>
總結(jié)
以上是生活随笔為你收集整理的MyBatis运行原理(二)SqlSession对象创建过程分析的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大白菜的pe怎么安装系统 大白菜pe系统
- 下一篇: Dubbo 入门介绍