日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

通过源码分析MyBatis的缓存

發(fā)布時(shí)間:2025/3/21 编程问答 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 通过源码分析MyBatis的缓存 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

前方高能! 本文內(nèi)容有點(diǎn)多,通過實(shí)際測(cè)試?yán)?#43;源碼分析的方式解剖MyBatis緩存的概念,對(duì)這方面有興趣的小伙伴請(qǐng)繼續(xù)看下去~

MyBatis緩存介紹

首先看一段wiki上關(guān)于MyBatis緩存的介紹:

MyBatis支持聲明式數(shù)據(jù)緩存(declarative data caching)。當(dāng)一條SQL語句被標(biāo)記為“可緩存”后,首次執(zhí)行它時(shí)從數(shù)據(jù)庫獲取的所有數(shù)據(jù)會(huì)被存儲(chǔ)在一段高速緩存中,今后執(zhí)行這條語句時(shí)就會(huì)從高速緩存中讀取結(jié)果,而不是再次命中數(shù)據(jù)庫。MyBatis提供了默認(rèn)下基于Java HashMap的緩存實(shí)現(xiàn),以及用于與OSCache、Ehcache、Hazelcast和Memcached連接的默認(rèn)連接器。MyBatis還提供API供其他緩存實(shí)現(xiàn)使用。

重點(diǎn)的那句話就是:MyBatis執(zhí)行SQL語句之后,這條語句就是被緩存,以后再執(zhí)行這條語句的時(shí)候,會(huì)直接從緩存中拿結(jié)果,而不是再次執(zhí)行SQL

這也就是大家常說的MyBatis一級(jí)緩存,一級(jí)緩存的作用域scope是SqlSession。

MyBatis同時(shí)還提供了一種全局作用域global scope的緩存,這也叫做二級(jí)緩存,也稱作全局緩存。

一級(jí)緩存

測(cè)試

同個(gè)session進(jìn)行兩次相同查詢:

@Test public void test() {SqlSession sqlSession = sqlSessionFactory.openSession();try {User user = (User)sqlSession.selectOne("org.format.mybatis.cache.UserMapper.getById", 1);log.debug(user);User user2 = (User)sqlSession.selectOne("org.format.mybatis.cache.UserMapper.getById", 1);log.debug(user2);} finally {sqlSession.close();} }

MyBatis只進(jìn)行1次數(shù)據(jù)庫查詢:

==> Preparing: select * from USERS WHERE ID = ? ==> Parameters: 1(Integer) <== Total: 1 User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014} User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014}

同個(gè)session進(jìn)行兩次不同的查詢:

@Test public void test() {SqlSession sqlSession = sqlSessionFactory.openSession();try {User user = (User)sqlSession.selectOne("org.format.mybatis.cache.UserMapper.getById", 1);log.debug(user);User user2 = (User)sqlSession.selectOne("org.format.mybatis.cache.UserMapper.getById", 2);log.debug(user2);} finally {sqlSession.close();} }

MyBatis進(jìn)行兩次數(shù)據(jù)庫查詢:

==> Preparing: select * from USERS WHERE ID = ? ==> Parameters: 1(Integer) <== Total: 1 User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014} ==> Preparing: select * from USERS WHERE ID = ? ==> Parameters: 2(Integer) <== Total: 1 User{id=2, name='FFF', age=50, birthday=Sat Dec 06 17:12:01 CST 2014}

不同session,進(jìn)行相同查詢:

@Test public void test() {SqlSession sqlSession = sqlSessionFactory.openSession();SqlSession sqlSession2 = sqlSessionFactory.openSession();try {User user = (User)sqlSession.selectOne("org.format.mybatis.cache.UserMapper.getById", 1);log.debug(user);User user2 = (User)sqlSession2.selectOne("org.format.mybatis.cache.UserMapper.getById", 1);log.debug(user2);} finally {sqlSession.close();sqlSession2.close();} }

MyBatis進(jìn)行了兩次數(shù)據(jù)庫查詢:

==> Preparing: select * from USERS WHERE ID = ? ==> Parameters: 1(Integer) <== Total: 1 User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014} ==> Preparing: select * from USERS WHERE ID = ? ==> Parameters: 1(Integer) <== Total: 1 User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014}

同個(gè)session,查詢之后更新數(shù)據(jù),再次查詢相同的語句:

@Test public void test() {SqlSession sqlSession = sqlSessionFactory.openSession();try {User user = (User)sqlSession.selectOne("org.format.mybatis.cache.UserMapper.getById", 1);log.debug(user);user.setAge(100);sqlSession.update("org.format.mybatis.cache.UserMapper.update", user);User user2 = (User)sqlSession.selectOne("org.format.mybatis.cache.UserMapper.getById", 1);log.debug(user2);sqlSession.commit();} finally {sqlSession.close();} }

更新操作之后緩存會(huì)被清除:

==> Preparing: select * from USERS WHERE ID = ? ==> Parameters: 1(Integer) <== Total: 1 User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014} ==> Preparing: update USERS SET NAME = ? , AGE = ? , BIRTHDAY = ? where ID = ? ==> Parameters: format(String), 23(Integer), 2014-10-12 23:20:13.0(Timestamp), 1(Integer) <== Updates: 1 ==> Preparing: select * from USERS WHERE ID = ? ==> Parameters: 1(Integer) <== Total: 1 User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014}

很明顯,結(jié)果驗(yàn)證了一級(jí)緩存的概念,在同個(gè)SqlSession中,查詢語句相同的sql會(huì)被緩存,但是一旦執(zhí)行新增或更新或刪除操作,緩存就會(huì)被清除

源碼分析

在分析MyBatis的一級(jí)緩存之前,我們先簡(jiǎn)單看下MyBatis中幾個(gè)重要的類和接口:

org.apache.ibatis.session.Configuration類:MyBatis全局配置信息類

org.apache.ibatis.session.SqlSessionFactory接口:操作SqlSession的工廠接口,具體的實(shí)現(xiàn)類是DefaultSqlSessionFactory

org.apache.ibatis.session.SqlSession接口:執(zhí)行sql,管理事務(wù)的接口,具體的實(shí)現(xiàn)類是DefaultSqlSession

org.apache.ibatis.executor.Executor接口:sql執(zhí)行器,SqlSession執(zhí)行sql最終是通過該接口實(shí)現(xiàn)的,常用的實(shí)現(xiàn)類有SimpleExecutor和CachingExecutor,這些實(shí)現(xiàn)類都使用了裝飾者設(shè)計(jì)模式

一級(jí)緩存的作用域是SqlSession,那么我們就先看一下SqlSession的select過程:

這是DefaultSqlSession(SqlSession接口實(shí)現(xiàn)類,MyBatis默認(rèn)使用這個(gè)類)的selectList源碼(我們例子上使用的是selectOne方法,調(diào)用selectOne方法最終會(huì)執(zhí)行selectList方法):

public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {try {MappedStatement ms = configuration.getMappedStatement(statement);List<E> result = executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);return result;} catch (Exception e) {throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);} finally {ErrorContext.instance().reset();} }

我們看到SqlSession最終會(huì)調(diào)用Executor接口的方法。

接下來我們看下DefaultSqlSession中的executor接口屬性具體是哪個(gè)實(shí)現(xiàn)類。

DefaultSqlSession的構(gòu)造過程(DefaultSqlSessionFactory內(nèi)部):

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, autoCommit);return new DefaultSqlSession(configuration, executor);} 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();} }

我們看到DefaultSqlSessionFactory構(gòu)造DefaultSqlSession的時(shí)候,Executor接口的實(shí)現(xiàn)類是由Configuration構(gòu)造的:

public Executor newExecutor(Transaction transaction, ExecutorType executorType, boolean autoCommit) {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, autoCommit);}executor = (Executor) interceptorChain.pluginAll(executor);return executor; }

Executor根據(jù)ExecutorType的不同而創(chuàng)建,最常用的是SimpleExecutor,本文的例子也是創(chuàng)建這個(gè)實(shí)現(xiàn)類。 最后我們發(fā)現(xiàn)如果cacheEnabled這個(gè)屬性為true的話,那么executor會(huì)被包一層裝飾器,這個(gè)裝飾器是CachingExecutor。其中cacheEnabled這個(gè)屬性是mybatis總配置文件中settings節(jié)點(diǎn)中cacheEnabled子節(jié)點(diǎn)的值,默認(rèn)就是true,也就是說我們?cè)趍ybatis總配置文件中不配cacheEnabled的話,它也是默認(rèn)為打開的。

現(xiàn)在,問題就剩下一個(gè)了,CachingExecutor執(zhí)行sql的時(shí)候到底做了什么?

帶著這個(gè)問題,我們繼續(xù)走下去(CachingExecutor的query方法):

public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {Cache cache = ms.getCache();if (cache != null) {flushCacheIfRequired(ms);if (ms.isUseCache() && resultHandler == null) { ensureNoOutParams(ms, parameterObject, boundSql);if (!dirty) {cache.getReadWriteLock().readLock().lock();try {@SuppressWarnings("unchecked")List<E> cachedList = (List<E>) cache.getObject(key);if (cachedList != null) return cachedList;} finally {cache.getReadWriteLock().readLock().unlock();}}List<E> list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);tcm.putObject(cache, key, list); // issue #578. Query must be not synchronized to prevent deadlocksreturn list;}}return delegate.<E>query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); }

其中Cache cache = ms.getCache();這句代碼中,這個(gè)cache實(shí)際上就是個(gè)二級(jí)緩存,由于我們沒有開啟二級(jí)緩存(二級(jí)緩存的內(nèi)容下面會(huì)分析),因此這里執(zhí)行了最后一句話。這里的delegate也就是SimpleExecutor,SimpleExecutor沒有Override父類的query方法,因此最終執(zhí)行了SimpleExecutor的父類BaseExecutor的query方法。

所以一級(jí)緩存最重要的代碼就是BaseExecutor的query方法!

BaseExecutor的屬性localCache是個(gè)PerpetualCache類型的實(shí)例,PerpetualCache類是實(shí)現(xiàn)了MyBatis的Cache緩存接口的實(shí)現(xiàn)類之一,內(nèi)部有個(gè)Map<Object, Object>類型的屬性用來存儲(chǔ)緩存數(shù)據(jù)。 這個(gè)localCache的類型在BaseExecutor內(nèi)部是寫死的。 這個(gè)localCache就是一級(jí)緩存!

接下來我們看下為何執(zhí)行新增或更新或刪除操作,一級(jí)緩存就會(huì)被清除這個(gè)問題。

首先MyBatis處理新增或刪除的時(shí)候,最終都是調(diào)用update方法,也就是說新增或者刪除操作在MyBatis眼里都是一個(gè)更新操作。

我們看下DefaultSqlSession的update方法:

public int update(String statement, Object parameter) {try {dirty = true;MappedStatement ms = configuration.getMappedStatement(statement);return executor.update(ms, wrapCollection(parameter));} catch (Exception e) {throw ExceptionFactory.wrapException("Error updating database. Cause: " + e, e);} finally {ErrorContext.instance().reset();} }

很明顯,這里調(diào)用了CachingExecutor的update方法:

public int update(MappedStatement ms, Object parameterObject) throws SQLException {flushCacheIfRequired(ms);return delegate.update(ms, parameterObject); }

這里的flushCacheIfRequired方法清除的是二級(jí)緩存,我們之后會(huì)分析。 CachingExecutor委托給了(之前已經(jīng)分析過)SimpleExecutor的update方法,SimpleExecutor沒有Override父類BaseExecutor的update方法,因此我們看BaseExecutor的update方法:

public int update(MappedStatement ms, Object parameter) throws SQLException {ErrorContext.instance().resource(ms.getResource()).activity("executing an update").object(ms.getId());if (closed) throw new ExecutorException("Executor was closed.");clearLocalCache();return doUpdate(ms, parameter); }

我們看到了關(guān)鍵的一句代碼: clearLocalCache(); 進(jìn)去看看:

public void clearLocalCache() {if (!closed) {localCache.clear();localOutputParameterCache.clear();} }

沒錯(cuò),就是這條,sqlsession沒有關(guān)閉的話,進(jìn)行新增、刪除、修改操作的話就是清除一級(jí)緩存,也就是SqlSession的緩存。

二級(jí)緩存

二級(jí)緩存的作用域是全局,換句話說,二級(jí)緩存已經(jīng)脫離SqlSession的控制了。

在測(cè)試二級(jí)緩存之前,我先把結(jié)論說一下:

二級(jí)緩存的作用域是全局的,二級(jí)緩存在SqlSession關(guān)閉或提交之后才會(huì)生效。

在分析MyBatis的二級(jí)緩存之前,我們先簡(jiǎn)單看下MyBatis中一個(gè)關(guān)于二級(jí)緩存的類(其他相關(guān)的類和接口之前已經(jīng)分析過):

org.apache.ibatis.mapping.MappedStatement:

MappedStatement類在Mybatis框架中用于表示XML文件中一個(gè)sql語句節(jié)點(diǎn),即一個(gè)<select />、<update />或者<insert />標(biāo)簽。Mybatis框架在初始化階段會(huì)對(duì)XML配置文件進(jìn)行讀取,將其中的sql語句節(jié)點(diǎn)對(duì)象化為一個(gè)個(gè)MappedStatement對(duì)象。

配置

二級(jí)緩存跟一級(jí)緩存不同,一級(jí)緩存不需要配置任何東西,且默認(rèn)打開。 二級(jí)緩存就需要配置一些東西。

本文就說下最簡(jiǎn)單的配置,在mapper文件上加上這句配置即可:

<cache/>

其實(shí)二級(jí)緩存跟3個(gè)配置有關(guān):

  • mybatis全局配置文件中的setting中的cacheEnabled需要為true(默認(rèn)為true,不設(shè)置也行)
  • mapper配置文件中需要加入<cache>節(jié)點(diǎn)
  • mapper配置文件中的select節(jié)點(diǎn)需要加上屬性u(píng)seCache需要為true(默認(rèn)為true,不設(shè)置也行)
  • 測(cè)試

    不同SqlSession,查詢相同語句,第一次查詢之后commit SqlSession:

    @Test public void testCache2() {SqlSession sqlSession = sqlSessionFactory.openSession();SqlSession sqlSession2 = sqlSessionFactory.openSession();try {String sql = "org.format.mybatis.cache.UserMapper.getById";User user = (User)sqlSession.selectOne(sql, 1);log.debug(user);// 注意,這里一定要提交。 不提交還是會(huì)查詢兩次數(shù)據(jù)庫sqlSession.commit();User user2 = (User)sqlSession2.selectOne(sql, 1);log.debug(user2);} finally {sqlSession.close();sqlSession2.close();} }

    MyBatis僅進(jìn)行了一次數(shù)據(jù)庫查詢:

    ==> Preparing: select * from USERS WHERE ID = ? ==> Parameters: 1(Integer) <== Total: 1 User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014} User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014}

    不同SqlSession,查詢相同語句,第一次查詢之后close SqlSession:

    @Test public void testCache2() {SqlSession sqlSession = sqlSessionFactory.openSession();SqlSession sqlSession2 = sqlSessionFactory.openSession();try {String sql = "org.format.mybatis.cache.UserMapper.getById";User user = (User)sqlSession.selectOne(sql, 1);log.debug(user);sqlSession.close();User user2 = (User)sqlSession2.selectOne(sql, 1);log.debug(user2);} finally {sqlSession2.close();} }

    MyBatis僅進(jìn)行了一次數(shù)據(jù)庫查詢:

    ==> Preparing: select * from USERS WHERE ID = ? ==> Parameters: 1(Integer) <== Total: 1 User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014} User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014}

    不同SqlSesson,查詢相同語句。 第一次查詢之后SqlSession不提交:

    @Test public void testCache2() {SqlSession sqlSession = sqlSessionFactory.openSession();SqlSession sqlSession2 = sqlSessionFactory.openSession();try {String sql = "org.format.mybatis.cache.UserMapper.getById";User user = (User)sqlSession.selectOne(sql, 1);log.debug(user);User user2 = (User)sqlSession2.selectOne(sql, 1);log.debug(user2);} finally {sqlSession.close();sqlSession2.close();} }

    MyBatis執(zhí)行了兩次數(shù)據(jù)庫查詢:

    ==> Preparing: select * from USERS WHERE ID = ? ==> Parameters: 1(Integer) <== Total: 1 User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014} ==> Preparing: select * from USERS WHERE ID = ? ==> Parameters: 1(Integer) <== Total: 1 User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014}

    源碼分析

    我們從在mapper文件中加入的<cache/>中開始分析源碼,關(guān)于MyBatis的SQL解析請(qǐng)參考另外一篇博客Mybatis解析動(dòng)態(tài)sql原理分析。接下來我們看下這個(gè)cache的解析:

    XMLMappedBuilder(解析每個(gè)mapper配置文件的解析類,每一個(gè)mapper配置都會(huì)實(shí)例化一個(gè)XMLMapperBuilder類)的解析方法:

    private void configurationElement(XNode context) {try {String namespace = context.getStringAttribute("namespace");if (namespace.equals("")) {throw new BuilderException("Mapper's namespace cannot be empty");}builderAssistant.setCurrentNamespace(namespace);cacheRefElement(context.evalNode("cache-ref"));cacheElement(context.evalNode("cache"));parameterMapElement(context.evalNodes("/mapper/parameterMap"));resultMapElements(context.evalNodes("/mapper/resultMap"));sqlElement(context.evalNodes("/mapper/sql"));buildStatementFromContext(context.evalNodes("select|insert|update|delete"));} catch (Exception e) {throw new BuilderException("Error parsing Mapper XML. Cause: " + e, e);} }

    我們看到了解析cache的那段代碼:

    private void cacheElement(XNode context) throws Exception {if (context != null) {String type = context.getStringAttribute("type", "PERPETUAL");Class<? extends Cache> typeClass = typeAliasRegistry.resolveAlias(type);String eviction = context.getStringAttribute("eviction", "LRU");Class<? extends Cache> evictionClass = typeAliasRegistry.resolveAlias(eviction);Long flushInterval = context.getLongAttribute("flushInterval");Integer size = context.getIntAttribute("size");boolean readWrite = !context.getBooleanAttribute("readOnly", false);Properties props = context.getChildrenAsProperties();builderAssistant.useNewCache(typeClass, evictionClass, flushInterval, size, readWrite, props);} }

    解析完cache標(biāo)簽之后會(huì)使用builderAssistant的userNewCache方法,這里的builderAssistant是一個(gè)MapperBuilderAssistant類型的幫助類,每個(gè)XMLMappedBuilder構(gòu)造的時(shí)候都會(huì)實(shí)例化這個(gè)屬性,MapperBuilderAssistant類內(nèi)部有個(gè)Cache類型的currentCache屬性,這個(gè)屬性也就是mapper配置文件中cache節(jié)點(diǎn)所代表的值:

    public Cache useNewCache(Class<? extends Cache> typeClass,Class<? extends Cache> evictionClass,Long flushInterval,Integer size,boolean readWrite,Properties props) {typeClass = valueOrDefault(typeClass, PerpetualCache.class);evictionClass = valueOrDefault(evictionClass, LruCache.class);Cache cache = new CacheBuilder(currentNamespace).implementation(typeClass).addDecorator(evictionClass).clearInterval(flushInterval).size(size).readWrite(readWrite).properties(props).build();configuration.addCache(cache);currentCache = cache;return cache; }

    ok,現(xiàn)在mapper配置文件中的cache節(jié)點(diǎn)被解析到了XMLMapperBuilder實(shí)例中的builderAssistant屬性中的currentCache值里。

    接下來XMLMapperBuilder會(huì)解析select節(jié)點(diǎn),解析select節(jié)點(diǎn)的時(shí)候使用XMLStatementBuilder進(jìn)行解析(也包括其他insert,update,delete節(jié)點(diǎn)):

    public void parseStatementNode() {String id = context.getStringAttribute("id");String databaseId = context.getStringAttribute("databaseId");if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) return;Integer fetchSize = context.getIntAttribute("fetchSize");Integer timeout = context.getIntAttribute("timeout");String parameterMap = context.getStringAttribute("parameterMap");String parameterType = context.getStringAttribute("parameterType");Class<?> parameterTypeClass = resolveClass(parameterType);String resultMap = context.getStringAttribute("resultMap");String resultType = context.getStringAttribute("resultType");String lang = context.getStringAttribute("lang");LanguageDriver langDriver = getLanguageDriver(lang);Class<?> resultTypeClass = resolveClass(resultType);String resultSetType = context.getStringAttribute("resultSetType");StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString()));ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType);String nodeName = context.getNode().getNodeName();SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));boolean isSelect = sqlCommandType == SqlCommandType.SELECT;boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect);boolean useCache = context.getBooleanAttribute("useCache", isSelect);boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false);// Include Fragments before parsingXMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);includeParser.applyIncludes(context.getNode());// Parse selectKey after includes and remove them.processSelectKeyNodes(id, parameterTypeClass, langDriver);// Parse the SQL (pre: <selectKey> and <include> were parsed and removed)SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);String resultSets = context.getStringAttribute("resultSets");String keyProperty = context.getStringAttribute("keyProperty");String keyColumn = context.getStringAttribute("keyColumn");KeyGenerator keyGenerator;String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX;keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true);if (configuration.hasKeyGenerator(keyStatementId)) {keyGenerator = configuration.getKeyGenerator(keyStatementId);} else {keyGenerator = context.getBooleanAttribute("useGeneratedKeys",configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))? new Jdbc3KeyGenerator() : new NoKeyGenerator();}builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,resultSetTypeEnum, flushCache, useCache, resultOrdered, keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets); }

    這段代碼前面都是解析一些標(biāo)簽的屬性,我們看到了最后一行使用builderAssistant添加MappedStatement,其中builderAssistant屬性是構(gòu)造XMLStatementBuilder的時(shí)候通過XMLMappedBuilder傳入的,我們繼續(xù)看builderAssistant的addMappedStatement方法:

    進(jìn)入setStatementCache:

    private void setStatementCache(boolean isSelect,boolean flushCache,boolean useCache,Cache cache,MappedStatement.Builder statementBuilder) {flushCache = valueOrDefault(flushCache, !isSelect);useCache = valueOrDefault(useCache, isSelect);statementBuilder.flushCacheRequired(flushCache);statementBuilder.useCache(useCache);statementBuilder.cache(cache); }

    最終mapper配置文件中的<cache/>被設(shè)置到了XMLMapperBuilder的builderAssistant屬性中,XMLMapperBuilder中使用XMLStatementBuilder遍歷CRUD節(jié)點(diǎn),遍歷CRUD節(jié)點(diǎn)的時(shí)候?qū)⑦@個(gè)cache節(jié)點(diǎn)設(shè)置到這些CRUD節(jié)點(diǎn)中,這個(gè)cache就是所謂的二級(jí)緩存!

    接下來我們回過頭來看查詢的源碼,CachingExecutor的query方法:

    進(jìn)入TransactionalCacheManager的putObject方法:

    public void putObject(Cache cache, CacheKey key, Object value) {getTransactionalCache(cache).putObject(key, value); }private TransactionalCache getTransactionalCache(Cache cache) {TransactionalCache txCache = transactionalCaches.get(cache);if (txCache == null) {txCache = new TransactionalCache(cache);transactionalCaches.put(cache, txCache);}return txCache; }

    TransactionalCache的putObject方法:

    public void putObject(Object key, Object object) {entriesToRemoveOnCommit.remove(key);entriesToAddOnCommit.put(key, new AddEntry(delegate, key, object)); }

    我們看到,數(shù)據(jù)被加入到了entriesToAddOnCommit中,這個(gè)entriesToAddOnCommit是什么東西呢,它是TransactionalCache的一個(gè)Map屬性:

    private Map<Object, AddEntry> entriesToAddOnCommit;

    AddEntry是TransactionalCache內(nèi)部的一個(gè)類:

    private static class AddEntry {private Cache cache;private Object key;private Object value;public AddEntry(Cache cache, Object key, Object value) {this.cache = cache;this.key = key;this.value = value;}public void commit() {cache.putObject(key, value);} }

    好了,現(xiàn)在我們發(fā)現(xiàn)使用二級(jí)緩存之后:查詢數(shù)據(jù)的話,先從二級(jí)緩存中拿數(shù)據(jù),如果沒有的話,去一級(jí)緩存中拿,一級(jí)緩存也沒有的話再查詢數(shù)據(jù)庫。有了數(shù)據(jù)之后在丟到TransactionalCache這個(gè)對(duì)象的entriesToAddOnCommit屬性中。

    接下來我們來驗(yàn)證為什么SqlSession commit或close之后,二級(jí)緩存才會(huì)生效這個(gè)問題。

    DefaultSqlSession的commit方法:

    public void commit(boolean force) {try {executor.commit(isCommitOrRollbackRequired(force));dirty = false;} catch (Exception e) {throw ExceptionFactory.wrapException("Error committing transaction. Cause: " + e, e);} finally {ErrorContext.instance().reset();} }

    CachingExecutor的commit方法:

    public void commit(boolean required) throws SQLException {delegate.commit(required);tcm.commit();dirty = false; }

    tcm.commit即 TransactionalCacheManager的commit方法:

    public void commit() {for (TransactionalCache txCache : transactionalCaches.values()) {txCache.commit();} }

    TransactionalCache的commit方法:

    public void commit() {delegate.getReadWriteLock().writeLock().lock();try {if (clearOnCommit) {delegate.clear();} else {for (RemoveEntry entry : entriesToRemoveOnCommit.values()) {entry.commit();}}for (AddEntry entry : entriesToAddOnCommit.values()) {entry.commit();}reset();} finally {delegate.getReadWriteLock().writeLock().unlock();} }

    發(fā)現(xiàn)調(diào)用了AddEntry的commit方法:

    public void commit() {cache.putObject(key, value); }

    發(fā)現(xiàn)了! AddEntry的commit方法會(huì)把數(shù)據(jù)丟到cache中,也就是丟到二級(jí)緩存中!

    關(guān)于為何調(diào)用close方法后,二級(jí)緩存才會(huì)生效,因?yàn)閏lose方法內(nèi)部會(huì)調(diào)用commit方法。本文就不具體說了。 讀者有興趣的話看一看源碼就知道為什么了。

    其他

    Cache接口簡(jiǎn)介

    org.apache.ibatis.cache.Cache是MyBatis的緩存接口,想要實(shí)現(xiàn)自定義的緩存需要實(shí)現(xiàn)這個(gè)接口。

    MyBatis中關(guān)于Cache接口的實(shí)現(xiàn)類也使用了裝飾者設(shè)計(jì)模式。

    我們看下它的一些實(shí)現(xiàn)類:

    簡(jiǎn)單說明:

    LRU – 最近最少使用的:移除最長(zhǎng)時(shí)間不被使用的對(duì)象。

    FIFO – 先進(jìn)先出:按對(duì)象進(jìn)入緩存的順序來移除它們。

    SOFT – 軟引用:移除基于垃圾回收器狀態(tài)和軟引用規(guī)則的對(duì)象。

    WEAK – 弱引用:更積極地移除基于垃圾收集器狀態(tài)和弱引用規(guī)則的對(duì)象。

    <cacheeviction="FIFO"flushInterval="60000"size="512"readOnly="true"/>

    可以通過cache節(jié)點(diǎn)的eviction屬性設(shè)置,也可以設(shè)置其他的屬性。

    cache-ref節(jié)點(diǎn)

    mapper配置文件中還可以加入cache-ref節(jié)點(diǎn),它有個(gè)屬性namespace。

    如果每個(gè)mapper文件都是用cache-ref,且namespace都一樣,那么就代表著真正意義上的全局緩存。

    如果只用了cache節(jié)點(diǎn),那僅代表這個(gè)這個(gè)mapper內(nèi)部的查詢被緩存了,其他mapper文件的不起作用,這并不是所謂的全局緩存。

    總結(jié)

    總體來說,MyBatis的源碼看起來還是比較輕松的,本文從實(shí)踐和源碼方面深入分析了MyBatis的緩存原理,希望對(duì)讀者有幫助。

    from:?https://www.cnblogs.com/fangjian0423/p/mybatis-cache.html

    總結(jié)

    以上是生活随笔為你收集整理的通过源码分析MyBatis的缓存的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。