缓存:首先持久层框架缓存不会优化sql来节省整个业务流程的时间,而是减少查询次数来缩短业务的执行时间。
缓存中存放数据:经常使用且对实时性要求并不高的内容。
mybatis缓存分为一级缓存与二级缓存。
一级缓存是自带的,使用时不用配置。
一级缓存作用域: 同一个sqlSession中:当同一个sqlSession在同一条sql且相同查询条件下,且中间无commit操作时,mybatis不会再次发起sql查询。
一级缓存测试:
1、两次查询再无commit()语句执行的时候(避免脏读),
sqlSession缓存了查询结果,再次查询时直接输出查询结果。
2 包含commit()的操作会刷新缓存区
commit后,将持续发送数据库sql请求。
二级缓存测试:
二级缓存:作用范围当前namespace下,可以跨sqlSession的。即相同namespace的查询且条件相同的sql,不同sqlSession发起请求不会对数据库发送sql。当任一sqlSession执行commit()(insert,update,delete)时,会清空整个namespace的缓存。
首先设置mybatis打开二级缓存。
1sqlMapConfig.xml中
<settings>
<setting name="cacheEnabled" value="true" />
</settings>
2xxxMapper.xml中配置<cache>标签。(mybatis有默认的cache接口实现类:org.apache.ibatis.cache.impl.PerpetualCache);
此图可看出,二级缓存和一级缓存都存在的情况下,先查询二级缓存。
commit();操作同一级缓存,会清空二级缓存。
ehcache结合mybatis:
因为mybatis的缓存是本地的(未测试)。服务器集群中sqlSession不会共享问题(未测试)。
所以结合ehcache分布式缓存来处理。
设置方法:
1引入mybatis-ehcache注意和mybatis版本一致性。
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
<!-- ehcache核心jar包 -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.11</version>
</dependency>
<!-- mysql -->
2设置xxxMapper.xml中<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>
3classpath下chcache.xml。
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
updateCheck="false" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<diskStore path="D:\ehcache" />
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120" maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap" />
</defaultCache>
</ehcache>
测试方法同二级缓存测试。
二级缓存弊端:
1、因为是相同namespace作用于,会导致多表查询的情况下
user - order 表, userOrderMapper.xml中的多表查询,当userMapper.xml中执行更新操作。userOrderMapper的关联查询是不会更新操作的。
2、因为二级缓存是相同namespace级别的。例如查询商品信息的需求,当执行商品的信息更新时,该namespace下的所有查询缓存都会被清理掉!!。