我们在学习Mybatis时,不可避免的学习到缓存模块。其中一级缓存失效网上的视频或者是文章一致的认为是四种情况:
1.不同的 SqlSession 对象对应不同的一级缓存,即使查询相同的数据,也要重新访问数据库;
2.同一个 SqlSession 对象,但是查询的条件不同;
3.同一个 SqlSession 对象两次查询期间执行了任何的“增删改”操作,无论这些“增删改”操作是否影响到了缓存的数据;
4.同一个 SqlSession 对象两次查询期间手动清空了缓存(调用了 SqlSession 对象的 clearCache() 方法)。
我认识第一和第二种情况不能称为"失效",要知道“失效”的意思是,缓存不存在了,而第一和第二种情况缓存还是存在的,我们可以通过代码验证一下,首先看第一种情况:
@Test
public void getEmpbyEid3() throws Exception {
SqlSession sqlSession = SqlSessionUtils.getSqlSession(true);
SqlSession sqlSession2 = SqlSessionUtils.getSqlSession(true);
CacheMapper mapper = sqlSession.getMapper(CacheMapper.class);
CacheMapper mapper2 = sqlSession2.getMapper(CacheMapper.class);
Emp empByCche = mapper.getEmpByCche(3);
Emp empByCche2 = mapper2.getEmpByCche(3);
Emp empByCche3 = mapper.getEmpByCche(3);
System.out.println(empByCche);
System.out.println(empByCche2);
System.out.println(empByCche3);
}
}
运行结果:
DEBUG 12-24 13:51:02,501 ==> Preparing: select * from t_emp_s where eid = ? (BaseJdbcLogger.java:137)
DEBUG 12-24 13:51:02,527 ==> Parameters: 3(Integer) (BaseJdbcLogger.java:137)
DEBUG 12-24 13:51:02,543 <== Total: 1 (BaseJdbcLogger.java:137)
DEBUG 12-24 13:51:02,551 ==> Preparing: select * from t_emp_s where eid = ? (BaseJdbcLogger.java:137)
DEBUG 12-24 13:51:02,551 ==> Parameters: 3(Integer) (BaseJdbcLogger.java:137)
DEBUG 12-24 13:51:02,553 <== Total: 1 (BaseJdbcLogger.java:137)
Emp{eid=3, empName='王五', sex='男', email='123@qq.com', age=23, dept=null}
Emp{eid=3, empName='王五', sex='男', email='123@qq.com', age=23, dept=null}
Emp{eid=3, empName='王五', sex='男', email='123@qq.com', age=23, dept=null}
Process finished with exit code 0
首先看第一种情况:我们通过不同的sqlsession访问同一个方法,由于是不同sqlsession,mybatis查询了两次数据库。但是执行第三个打印语句时,并没有再查询数据库,由此我们可以得知,第一个sqlsession的缓存并没有失效。
第二种情况:
@Test
public void getEmpbyEid2() throws Exception {
SqlSession sqlSession = SqlSessionUtils.getSqlSession(true);
CacheMapper mapper = sqlSession.getMapper(CacheMapper.class);
Emp empByCche = mapper.getEmpByCche(3);
Emp empByCche2 = mapper.getEmpByCche(1);
Emp empByCche3 = mapper.getEmpByCche(3);
System.out.println(empByCche);
System.out.println(empByCche2);
System.out.println(empByCche3);
}
运行结果:
DEBUG 12-24 13:59:56,400 ==> Preparing: select * from t_emp_s where eid = ? (BaseJdbcLogger.java:137)
DEBUG 12-24 13:59:56,420 ==> Parameters: 3(Integer) (BaseJdbcLogger.java:137)
DEBUG 12-24 13:59:56,442 <== Total: 1 (BaseJdbcLogger.java:137)
DEBUG 12-24 13:59:56,442 ==> Preparing: select * from t_emp_s where eid = ? (BaseJdbcLogger.java:137)
DEBUG 12-24 13:59:56,443 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:137)
DEBUG 12-24 13:59:56,444 <== Total: 1 (BaseJdbcLogger.java:137)
Emp{eid=3, empName='王五', sex='男', email='123@qq.com', age=23, dept=null}
Emp{eid=1, empName='张三', sex='男', email='123@qq.com', age=23, dept=null}
Emp{eid=3, empName='王五', sex='男', email='123@qq.com', age=23, dept=null}
Process finished with exit code 0
我们同样可以查看,执行不同的查询条件,mybatis会再次查询数据库,但是不会使得同一个sqlsessin同一个方法,同一个查询条件的缓存“失效”。
以上是我个人观点,如有错误,欢迎指正。