Java学习-MyBatis缓存

MyBatis缓存

MyBatis一级缓存
  • 一级缓存是SqlSession级别的,通过同一个SqlSession查询的数据会被缓存,下次查询相同的数据,就会从缓存中直接获取,不会去访问数据库
  • 一级缓存失效的四种情况
    • 不同的SqlSession对应不同的一级缓存
    • 同一个SqlSession但查询条件不同
    • 同一个SqlSession两次查询期间执行了任何一次增删改操作
    • 同一个SqlSession两次查询期间手动清除了缓存
  @Test
    public void testGetEmp() {
   
        SqlSession sqlSession1 = SqlSessionUtils.getSqlSession();
        CacheMapper mapper1 = sqlSession1.getMapper(CacheMapper.class);
        Emp emp1 = mapper1.getEmpById(4);
        System.out.println(emp1);
        //手动清空缓存
        sqlSession1.clearCache();
        Emp emp2 = mapper1.getEmpById(4);
        System.out.println(emp2);
        //执行插入操作
        mapper1.insertEmp(new Emp(null,"jack",23,"男","jack@qq.com"));
        CacheMapper mapper2 = sqlSession1.getMapper(CacheMapper.class);
        Emp emp3 = mapper2.getEmpById(4);
        System.out.println(emp3);
        //使用不同的SqlSession
        SqlSession sqlSession2 = SqlSessionUtils.getSqlSession();
        CacheMapper mapper3 = sqlSession2.getMapper(CacheMapper.class);
        Emp emp4 = mapper3.getEmpById(4);
        System.out.println(emp4);
    }
/*
  ①不同的SqlSession查询相同的数据缓存失效
  ②同一个SqlSession两次查询期间执行了插入操作,导致缓存失效
  ③同一个SqlSession两次查询期间手动清空了缓存
*/
DEBUG 06-14 14:45:16,001 ==>  Preparing: select * from t_emp where eid=? (BaseJdbcLogger.java:137) 
DEBUG 06-14 14:45:16,021 ==> Parameters: 4(Integer) (BaseJdbcLogger.java:137) 
DEBUG 06
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值