二级缓存
开启全局二级缓存
<setting name="cacheEnabled" value="true"/>
去mapper.xml中配置使用二级缓存
<cache></cache>
<cache eviction="FIFO" flushInterval="60000" readOnly="false" size="1024" ></cache>
- cache中的配置
- type = “”:指定自定义缓存的全类名;实现Cache接口即可;
我们的POJO需要实现序列化接口
测试
@Testpublic void testSecondLevelCache() throws IOException {SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();SqlSession sqlSession = sqlSessionFactory.openSession();SqlSession sqlSession1 = sqlSessionFactory.openSession();try{EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);EmployeeMapper mapper1 = sqlSession1.getMapper(EmployeeMapper.class);Employee emp01 = mapper.getEmpById(1);System.out.println(emp01);sqlSession.close();Employee emp02 = mapper1.getEmpById(1);System.out.println(emp02);sqlSession1.close();}finally {sqlSession.close();}}
- 二级缓存失效
只有会话提交或者关闭以后,一级缓存中的数据才会转移到二级缓存中
@Testpublic void testSecondLevelCache() throws IOException {SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();SqlSession sqlSession = sqlSessionFactory.openSession();SqlSession sqlSession1 = sqlSessionFactory.openSession();try{EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);EmployeeMapper mapper1 = sqlSession1.getMapper(EmployeeMapper.class);Employee emp01 = mapper.getEmpById(1);System.out.println(emp01);Employee emp02 = mapper1.getEmpById(1);System.out.println(emp02);sqlSession.close();sqlSession1.close();}finally {}}