怎么样开启二级缓存?
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,

查询的时候却只执行了一次。并且得到的结果是同一个,说明是二级缓存。
本文介绍了如何开启和理解MyBatis的二级缓存。首先,虽然全局缓存默认开启,但需要在映射器中进行配置。二级缓存的工作机制是,当一个会话查询数据后,数据会被存入一级缓存,会话关闭时,一级缓存中的数据会移至二级缓存。在新的会话中,可以从中获取之前查询过的数据,从而减少数据库查询次数。通过示例代码展示了两个会话查询同一数据时,只执行一次查询并从二级缓存获取结果的情况。
4995

被折叠的 条评论
为什么被折叠?



