当前位置:   article > 正文

一级缓存(默认开始sqlsession级别)和 二级缓存(testTwoCache)_sqlsession缓存

sqlsession缓存

一级缓存(默认开始sqlsession级别)


一级缓存失效的四种情况:
1.不同的sqlsession对应不同的缓存
2.同一个sqlsession但是查询条件不同
3.同一个sqlsession两次查询期间执行了任何一个增删改的操作(testgetEmpByEid3)
4.同一个sqlsession两次查询期间手动清空了缓存

  1. @Test
  2. public void getEmpByEmpIdTest(){
  3. SqlSession sqlSession1 = SqlSessionUtil.getSqlSession();
  4. CacheMapper mapper1 = sqlSession1.getMapper(CacheMapper.class);
  5. //此处用的是同一个Sqlsession
  6. Emp emp1 = mapper1.getEmpByEmpId(1);//第一条emp1
  7. System.out.println(emp1);
  8. Emp emp2 = mapper1.getEmpByEmpId(1);//第二条emp2
  9. System.out.println(emp2);
  10. }

一级缓存失效情况

  1. @Test
  2. public void testgetEmpByEid2(){
  3. SqlSession sqlsession1 = SQLsession.getSqlsession();
  4. CacheMapper mapper1 = sqlsession1.getMapper(CacheMapper.class);
  5. Emp empByEid1 = mapper1.getEmpByEid(1);
  6. System.out.println(empByEid1);
  7. SqlSession sqlsession2 = SQLsession.getSqlsession();
  8. CacheMapper mapper2 = sqlsession2.getMapper(CacheMapper.class);
  9. Emp empByEid2 = mapper2.getEmpByEid(1);
  10. System.out.println(empByEid2);
  11. }
  1. @Test
  2. public void testgetEmpByEid3(){
  3. SqlSession sqlsession = SQLsession.getSqlsession();
  4. CacheMapper mapper = sqlsession.getMapper(CacheMapper.class);
  5. Emp empByEid1 = mapper.getEmpByEid(1);
  6. System.out.println(empByEid1);
  7. mapper.insertEmp(new Emp(null,"sdd",12,"1","1",null));
  8. Emp empByEid2 = mapper.getEmpByEid(1);
  9. System.out.println(empByEid2);
  10. }
  1. @Test
  2. public void testTwoCache(){
  3. //不能使用工具类的形式创建SQLsession
  4. try {
  5. InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
  6. SqlSessionFactory builder = new SqlSessionFactoryBuilder().build(in);
  7. SqlSession sqlSession1 = builder.openSession(true);
  8. CacheMapper mapper1 = sqlSession1.getMapper(CacheMapper.class);
  9. System.out.println(mapper1.getEmpByEid(1));
  10. sqlSession1.close();
  11. SqlSession sqlSession2 = builder.openSession(true);
  12. CacheMapper mapper2 = sqlSession2.getMapper(CacheMapper.class);
  13. System.out.println(mapper2.getEmpByEid(1));
  14. sqlSession2.close();
  15. } catch (IOException e) {
  16. e.printStackTrace();
  17. }
  18. }

二级缓存(testTwoCache)


1.在核心配置文件中设置全局配置属性cacheEnabled="ture",默认为ture不需要设置
2.在映射文件中配置标签<cache/>
3.二级缓存必须在sqlSession关闭或提交后有效
4.查询的数据所转换的实体类类型必须实现序列化的接口(implements Serializable )
二级缓存失效的情况:
两次查询中间执行了任意的增删改查,会使一级缓存和二级缓存同时失效

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/159889
推荐阅读
相关标签
  

闽ICP备14008679号