Mybatis二级缓存

怎么样开启二级缓存?

1.开启全局缓存(虽然默认就是开启的)

2.在映射器中加一行

它的里面有很多属性可以添加:

 

工作机制:

- 一个会话查询一条数据,这个数据就会被放到当前会话的一级缓存中去;

- 如果当前会话被关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,一级缓存中的数据被保存到二级缓存中。(死了就遗传给儿子)

- 新的会话查询信息,就可以从二级缓存中获取内容

- 不同的mapper查出的数据会放到自己对应的缓存中去。

例子

  @Test
    public void test02() throws IOException {
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        Student studentById = mapper.getStudentById(1);
        System.out.println(studentById);
        sqlSession.close();
        SqlSession sqlSession1 = MybatisUtils.getSqlSession();
        StudentMapper mapper1 = sqlSession1.getMapper(StudentMapper.class);
        Student studentById1 = mapper1.getStudentById(1);
        System.out.println(studentById1);
        System.out.println(studentById1==studentById);
        sqlSession1.close();


    }

可以看到这里创建了两个sqlSession,

 

查询的时候却只执行了一次。并且得到的结果是同一个,说明是二级缓存。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值