1.加入ehcache的相关jar包:(注意ehcache的核心jar包依赖两个日志包)
ehcache-core-2.4.3.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.7.21.jar
2.加入mybatis中ehcache的适配包(版本可以自己选择自己喜欢的)
mybatis-ehcache-1.0.3.jar
3.在类路径下添加ehcache的ehcache.xml文件
最后在Mapper中使用ehcache提供的二级缓存的实现:
<?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="zhang.mybatis.dao.EmployeeMapper">
<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>
</mapper>
若在其他的mapper.xml文件中需要使用可以通过使用标签引用其他mapper.xml中配置的缓存
<?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="zhang.mybatis.dao.DepartmentMapper">
<!-- 引入缓存 -->
<cache-ref namespace="zhang.mybatis.dao.EmployeeMapper"/>
</mapper>
最后进行测试:
//测试整合ehcache的二级缓存
@Test
public void testsecondelevelcachedepartmnet() throws IOException{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
SqlSession openSession2 = sqlSessionFactory.openSession();
try {
DepartmentMapper mapper = openSession.getMapper(DepartmentMapper.class);
DepartmentMapper mapper2 = openSession2.getMapper(DepartmentMapper.class);
Department departmentById = mapper.getDepartmentById(1);
System.out.println(departmentById);
openSession.close();
Department departmentById2 = mapper2.getDepartmentById(1);
System.out.println(departmentById2);
} catch (Exception e) {
e.printStackTrace();
}finally {
openSession2.close();
}
}