mybatis 缓存的一些测试

环境和spring 事务的传播级别一致

  @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Test
    public void testOneLevelCache(){
        SqlSession session = sqlSessionFactory.openSession();
        StudentMapper mapper = session.getMapper(StudentMapper.class);
        System.out.println("第一次查询");
        Student student = mapper.getById(1);
        System.out.println(student);
        System.out.println("第二次查询");
        Student student2 = mapper.getById(1);
        System.out.println(student2);
        session.commit();
        session.close();
    }

 

结果:只是打印一次sql

下面测试commit是否会清空缓存

 @Test
    public void testCommit(){
        SqlSession oldSession = sqlSessionFactory.openSession();
        System.out.println("获取的session"+oldSession);
        StudentMapper mapper = oldSession.getMapper(StudentMapper.class);
        Student student = mapper.getById(1);
        System.out.println("第一次查询结果"+student);
        oldSession.commit();
        Student student2 = mapper.getById(1);
        System.out.println("第二次查询结果"+student2);
    }

结果:打印了两条sql,缓存被清空了

1、修改第二次查询ID为2

结果:打印两次sql

2、修改为关闭sqlSession后,在此查询相同sql,如下所示

 @Test
    public void testOneLevelCache(){
        SqlSession oldSession = sqlSessionFactory.openSession();
        System.out.println("第一次获取的session"+oldSession);
        StudentMapper mapper = oldSession.getMapper(StudentMapper.class);
        System.out.println("第一次查询结果");
        Student student = mapper.getById(1);
        System.out.println(student);
        oldSession.commit();
        oldSession.close();

        SqlSession newSession = sqlSessionFactory.openSession();
        StudentMapper newMapper = newSession.getMapper(StudentMapper.class);
        System.out.println("重新获取的session"+newSession);
        System.out.println("第二次查询结果");
        Student student2 = newMapper.getById(1);
        System.out.println(student2);
        newSession.commit();
        newSession.close();
    }

结果:两个打印session对象必然是不同的,发现打印两条一样的sql

综上所述:

    在sqlSession生命周期内,是存在缓存的。也就是mybatis的一级缓存,是个默认配置。

3、清空sqlSession中的缓存,同样是执行相同sql

 @Test
    public void testOneLevelCache2(){
        SqlSession oldSession = sqlSessionFactory.openSession();
        System.out.println("第一次获取的session"+oldSession);
        StudentMapper mapper = oldSession.getMapper(StudentMapper.class);
        System.out.println("第一次查询结果");
        Student student = mapper.getById(1);
        System.out.println(student);
        oldSession.clearCache();
        System.out.println("第二次查询结果");
        Student student2 = mapper.getById(1);
        System.out.println(student2);
    }

结果:同样是两条sql

4、做个测试,同个sqlSession获取到的mapper是否一致,是否会影响到前面mybatis一级缓存的测试结果

    @Test
    public void testOneLevelCache03(){
        SqlSession oldSession = sqlSessionFactory.openSession();
        System.out.println("第一次获取的session"+oldSession);
        StudentMapper mapper = oldSession.getMapper(StudentMapper.class);
        System.out.println("第一次的mapper "+mapper);
        Student student = mapper.getById(1);
        System.out.println("第一次的查询结果 "+student);
        StudentMapper mapper2 = oldSession.getMapper(StudentMapper.class);
        System.out.println("第二次的mapper "+mapper2);
        Student student2 = mapper2.getById(1);
        System.out.println("第二次的查询结果 "+student2);
    }

结果:

第一次获取的sessionorg.apache.ibatis.session.defaults.DefaultSqlSession@358ab600
第一次的mapper org.apache.ibatis.binding.MapperProxy@e26af6

JDBC Connection [HikariProxyConnection@657628458 wrapping com.mysql.jdbc.JDBC4Connection@1ee47d9e] will not be managed by Spring
==>  Preparing: select * from Student where id = ? 
==> Parameters: 1(Integer)

<==    Columns: id, name, age
<==        Row: 1, stu01, 22
<==      Total: 1
第一次的查询结果 Student{id=1, name='stu01', age=22}
第二次的mapper org.apache.ibatis.binding.MapperProxy@77f905e3
第二次的查询结果 Student{id=1, name='stu01', age=22}

结论:发现sql还是一条,所以一级缓存是sqlSession生命周期内,与mapper实例是否同一个没关系。

5、缓存何时刷新,如果我们没有主动clearCache,修改下面代码,在两次查询中穿插DML语句


    @Test
    public void testOneLevelCache04(){
        SqlSession oldSession = sqlSessionFactory.openSession();
        StudentMapper mapper = oldSession.getMapper(StudentMapper.class);
        Student student = mapper.getById(1);
        System.out.println("第二次的查询结果 "+student);
        int record = mapper.updateNameById(1,"cherish");
        Student student2 = mapper.getById(1);
        System.out.println("第二次的查询结果 "+student2);
        oldSession.close();
    }

结果: 执行了三条语句,第二次查询结果为更新后的结果,所以,缓存在更新操作后已经失效了。后面查询并非从缓存中查询。

 

二级缓存测试

老师模块Mapper来做测试


@CacheNamespace()
public interface TeacherMapper {
    @Insert("insert into teacher(name,age) values(#{name},#{age})")
    int addTeacher(Teacher teacher);


//    用于测试二级缓存
    @Select("select * from teacher where id = #{stuID}")
    Student getById(Integer stuID);

    @Update("update teacher set name = #{ name } where id = #{ id }")
    int updateNameById(@Param(value = "id") Integer id, @Param(value = "name") String name);
}

1、如下测试,两次发起一样的查询


    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Test
    public void testTwoLevelCache01(){
        SqlSession oldSession = sqlSessionFactory.openSession();
        TeacherMapper oldMapper = oldSession.getMapper(TeacherMapper.class);
        Teacher teacher1 = oldMapper.getById(1);
        System.out.println("第一次查询结果 "+teacher1);
        SqlSession newSession = sqlSessionFactory.openSession();
        TeacherMapper newMapper = newSession.getMapper(TeacherMapper.class);
        Teacher teacher2 = newMapper.getById(1);
        System.out.println("第二次查询结果 "+teacher2);
    }

结果:发起两次sql查询

结论:二级缓存失效(不同的sqlSession,在前面一级缓存中测试过了,不会使用一级缓存)

2、session commit测试,在第一次查询后添加一次如下提交

oldSession.commit();

结果:

分析:来自缓存异常,提示需要标识序列化

解决:

运行结果:

缓存命中率日志提示,同时sql语句只打印一条。也就说明二级缓存生效了

3、做一个测试,就是第一次commit,后面几次打开相同操作都不commit,打印看看命中率有啥变化

@Test
    public void testTwoLevelCache02(){
        SqlSession oldSession = sqlSessionFactory.openSession();
        TeacherMapper oldMapper = oldSession.getMapper(TeacherMapper.class);
        Teacher teacher1 = oldMapper.getById(1);
        System.out.println("第一次查询结果 "+teacher1);
        oldSession.commit();
        SqlSession newSession = sqlSessionFactory.openSession();
        TeacherMapper newMapper = newSession.getMapper(TeacherMapper.class);
        Teacher teacher2 = newMapper.getById(1);
        System.out.println("第二次查询结果 "+teacher2);

        SqlSession thridSession = sqlSessionFactory.openSession();
        TeacherMapper thirdMapper = thridSession.getMapper(TeacherMapper.class);
        Teacher teacher3 = thirdMapper.getById(1);
        System.out.println("第三次查询结果 "+teacher3);

        SqlSession forthSession = sqlSessionFactory.openSession();
        TeacherMapper forthMapper = forthSession.getMapper(TeacherMapper.class);
        Teacher teacher04 = forthMapper.getById(1);
        System.out.println("第四次查询结果 "+teacher04);
    }

结果

命中率:不断提高

4、在第三次和第四次操作中,穿插一个DML更新

        SqlSession middleSession = sqlSessionFactory.openSession();
        TeacherMapper mapper = middleSession.getMapper(TeacherMapper.class);
        int zls = mapper.updateNameById(1, "詹老师");

结果:前面三次查询是:第一次操作查询一条sql,第二次、第三次都是命中缓存。

中间DML更新打印了一次sql,第四次查询则又是命中缓存,缓存中的数据是未更新前的数据,所以缓存未更新。

5、在修改后加上commit,如下所示:

  SqlSession middleSession = sqlSessionFactory.openSession();
        TeacherMapper mapper = middleSession.getMapper(TeacherMapper.class);
        int zls = mapper.updateNameById(1, "詹老师");
        middleSession.commit();

结果:

前面三次查询及更新操作未变,而第四次查询则是打印一条sql,

结论:缓存更新了。DML语句会刷新二级缓存,并且生成缓存和刷新缓存都需要commit操作

6、这些默认配置在哪?


@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface CacheNamespace {
    映射语句文件中的所有 select 语句的结果将会被缓存。
    映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。

    Class<? extends Cache> implementation() default PerpetualCache.class;
    缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
    Class<? extends Cache> eviction() default LruCache.class;
    缓存不会定时进行刷新(也就是说,没有刷新间隔)。
    long flushInterval() default 0L;
    缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。
    int size() default 1024;
    缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他 
    调用者或线程所做的潜在修改。
    boolean readWrite() default true;

    boolean blocking() default false;

    Property[] properties() default {};
}

下面是部分网络资料

http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html#cache

提示:   缓存只作用于 cache 标签所在的映射文件中的语句。如果你混合使用 Java API 和 XML 映射文件,在共用接口中的语句将不会被默认缓存。你需要使用 @CacheNamespaceRef 注解指定缓存作用域。

 

在使用二级缓存中,查阅了些资料,其中

https://blog.csdn.net/isea533/article/details/44566257

的说法:避免使用二级缓存,我觉得很有道理

PS:缓存和Mapper的namespace是紧关联的,如果使用这缓存,容易出现多表之间关联问题,在写大量业务代码时还需要花心思去思考缓存那些事,开发效率应该会更低吧,而且团队中并非所有开发者对缓存都能够熟悉,所以将缓存实现在业务层的可控缓存中可能是个更好的解决方案。

1、可以使用Redis等NoSQL来缓存,在更新数据后清空缓存,这些缓存l逻辑都通过代码中维护,也是一个解决方案。

 

以上是博主对mybatis 缓存的一些学习笔记,方便以后查阅。好记性不如“烂笔头“,何况也不烂。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值