介绍
本篇文章给大家分享的是有关Mybatis中缓存的方式有哪些,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
通过查看源码可知,一级缓存是绑定sqSsession中的,所以每次查询sqlSession不同就失效,相同的sqlSession可以使用一级缓存。
Mybatis默认sqlSession: org.apache.ibatis.session.defaults.DefaultSqlSession
构造方法中传入执行人(查询执行对象)
, public DefaultSqlSession (Configuration 配置,Executor 执行人,,boolean 自动提交),{ 时间=this.configuration 才能;配置; 时间=this.executor 才能;执行器; 时间=this.dirty 才能;假; 时间=this.autoCommit 才能;自动提交; 以前,}>执行者中携带一级缓存成员:
, protected BaseExecutor (Configuration 配置,Transaction 事务),{ 时间=this.transaction 才能;事务; 时间=this.deferredLoads 才能;new ConcurrentLinkedQueue<在(); 时间=this.localCache 才能;new PerpetualCache (“LocalCache");,//默认一级缓存 时间=this.localOutputParameterCache 才能;new PerpetualCache (“LocalOutputParameterCache"); 时间=this.closed 才能;假; 时间=this.configuration 才能;配置; 时间=this.wrapper 才能;; 以前,}>查询使用一级缓存逻辑
<代码> org.apache.ibatis.executor.BaseExecutor.query() 代码>
, public & lt; E>, List,查询(MappedStatement 女士,Object 参数,,RowBounds rowBounds,, ResultHandler resultHandler,, CacheKey 关键,,BoundSql boundSql), throws SQLException { ErrorContext.instance才能().resource (ms.getResource ()) .activity (“executing a query") .object (ms.getId ()); ,, List<才能;E>,列表; try {才能 ,,queryStack + +; ,,//localCache 一级缓存 ,,list =, resultHandler ==, null ?, (List List , queryFromDatabase (MappedStatement 女士,Object 参数,,RowBounds rowBounds,, ResultHandler resultHandler,, CacheKey 关键,,BoundSql boundSql), throws SQLException { List<才能;E>,列表; localCache.putObject才能(关键,EXECUTION_PLACEHOLDER); try {才能 ,,list =, doQuery (ms,时间参数,大敌;;rowBounds, resultHandler,, boundSql); ,,},{finally ,,localCache.removeObject(关键);//将一级缓存清除 ,,} localCache.putObject才能(关键,,列表);//返回查询结果之前,先放入一级缓存,刷新 if 才能;(ms.getStatementType (),==, StatementType.CALLABLE), { ,,localOutputParameterCache.putObject(关键,参数); ,,} return 才能;列表; 以前,}> 二级缓存
二级缓存映射器中的,默认是开启的,但需要在映射文件mapper.xml中添加& lt;缓存/祝辞标签
& lt; mapper 名称空间=皍serMapper"比; & lt;缓存/祝辞& lt; !——,添加缓存标签表示此映射器使用二级缓存,——比; & lt;/mapper>配置假可以关闭二级缓存
二级缓存的解析
<代码> org.apache.ibatis.builder.xml。XMLMapperBuilder 代码>
, private void configurationElement (XNode 上下文),{ try {才能 ,,//? ,,cacheElement (context.evalNode (“cache")),,//解析缓存标签 ,,},catch (Exception e), { ,,throw new  BuilderException (“Error  parsing Mapper XML只,XML 位置is & # 39;“, +, resource +,“& # 39;只原因:,“,+,e, e); ,,} ,} ,private void  cacheElement (XNode 上下文),{ if 才能;(context !=, null), {,//if hava cache tag 如果有缓存标签才执行下面的逻辑 ,,String type =, context.getStringAttribute (“type",,“PERPETUAL"); ,,Class<?, extends Cache>, typeClass =, typeAliasRegistry.resolveAlias(类型); null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null nullMybatis中缓存的方式有哪些