Mybatis本身是一个持久层框架,它不是专门的缓存框架,所以它对缓存的实现不够好,不能支持分布式。
Ehcache是一个分布式的缓存框架。

Cache是一个接口,它的默认实现是mybatis的PerpetualCache。如果想整合mybatis的二级缓存,那么实现Cache接口即可。

在maven配置文件中添加

<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.2.1</version>
</dependency>

在src文件下添加ehcache配置文件

ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>

<!--
maxElementsInMemory :设置基于内存的缓存中可存放的对象最大数目
eternal:设置对象是否为永久的,true表示永不过期,此时将忽略
timeToIdleSeconds 和 timeToLiveSeconds属性; 默认值是false
timeToIdleSeconds:设置对象空闲最长时间,以秒为单位, 超过这个时间,对象过期。当对象过期时,EHCache会把它从缓存中清除。如果此值为0,表示对象可以无限期地处于空闲状态。
timeToLiveSeconds:设置对象生存最长时间,超过这个时间,对象过期。如果此值为0,表示对象可以无限期地存在于缓存中. 该属性值必须大于或等于 timeToIdleSeconds 属性值
overflowToDisk:设置基于内在的缓存中的对象数目达到上限后,是否把溢出的对象写到基于硬盘的缓存中
diskPersistent 当jvm结束时是否持久化对象 true false 默认是false
diskExpiryThreadIntervalSeconds 指定专门用于清除过期对象的监听线程的轮询时间
memoryStoreEvictionPolicy - 当内存缓存达到最大,有新的element加入的时候, 移除缓存中element的策略。默认是LRU(最近最少使用),可选的有LFU(最不常使用)和FIFO(先进先出)
-->
</ehcache>

在mybatis全局配置文件中开启二级缓存

<settings>
<setting name="cacheEnabled" value="true"/>
</settings>

在需要二级缓存的sqlmapper中配置ehcache

将默认的perpetualCache改org.mybatis.caches.ehcache.EhcacheCache

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="edu.ccit.cn.mapper.UserMapper">
<!--
Mybatis默认使用perpetualCache缓存对象 使用二级缓存需要实现cache接口,
EhcacheCache继承了接口
-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>
<select id="findUserById" resultType="User">
select * from user where id=#{?}
</select>
</mapper>

测试类

@Test
//二级缓存默认关闭 范围在SqlSessionFactory
/*
<cache>标签的属性
  eviction:缓存清除策略
  flushInterval:刷新间隔,单位毫秒
  size:设置大小,默认是1024
  readOnly:是否只读(不写入文件),默认是false,需要实体类实现序列化接口
  type:用于自定义缓存机制,提供一个自定义类的全限定路径,自定义类需要实现CaChe接口
*/
public void method02_Level2Cache(){
SqlSession sqlSession = ssf.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User userById = mapper.findUserById(1);
System.out.println(userById);
sqlSession.close();

SqlSession sqlSession1 = ssf.openSession();
UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
User userById1 = mapper1.findUserById(1);
System.out.println(userById1);
sqlSession1.close();
}