1、引入jar包:
<!-- mybatis二级缓存使用ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.11</version>
</dependency>
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
2、在mapper.xml中添加配置:
<!--添加缓存配置-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache">
<property name="timeToIdleSeconds" value="60"></property><!--<!–当缓存闲置60秒后销毁–>-->
<property name="timeToLiveSeconds" value="160"></property><!--<!–缓存存在160秒后销毁–>-->
<property name="maxEntriesLocalHeap" value="1000"></property><!--堆内存中最大缓存对象数,0没有限制(必须设置)-->
<property name="maxEntriesLocalDisk" value="1000000"></property><!-- 硬盘最大缓存个数。 -->
<!--当达到maxElementsInMemory时,如何强制进行驱逐默认使用"最近使用(LRU)"策略,其它还有先入先出FIFO,最少使用LFU,较少使用LRU-->
<property name="memoryStoreEvictionPolicy" value="LFU"></property>
</cache>
注意:
(1)当为select语句时:
flushCache默认为false,表示任何时候语句被调用,都不会去清空本地缓存和二级缓存。
useCache默认为true,表示会将本条语句的结果进行二级缓存,所以希望该查询不进行缓存,则手动将useCache=false。
(2)当为insert、update、delete语句时:
flushCache默认为true,表示任何时候语句被调用,都会导致本地缓存和二级缓存被清空。
useCache属性在该情况下没有。