怎么样开启二级缓存?
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,
查询的时候却只执行了一次。并且得到的结果是同一个,说明是二级缓存。