Mybatis基础(八)
查询缓存
一级缓存(Mybatis自带)
一级缓存将查询信息放入SqlSession对象中,SqlSession对象放在内存中。
一级缓存的清理
当使用SqlSession对象的commit方法,则SqlSession对象中的数据清除。
二级缓存(需手动开启)
二级缓存的来源:
- Mybatis自带的二级缓存
- 第三方的二级缓存
Mybatis自带的二级缓存
同一个namespace(mapper标签的属性)生成的mapper对象共享缓存。
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
StudentMapper studentMapper2 = session.getMapper(StudentMapper.class);
studentMapper与studentMapper2共享同一块缓存区。因为Mapper是由mapper类名与报名决定的(也就是namespace)。
注意!二级缓存与一级缓存不一样,二级缓存数据存放在硬盘中。所以会调用序列化类。
当查询后会将查询结果序列化到硬盘(二级缓存),所以对查询结果类应该进行序列化。
开启二级缓存
- 配置conf.xml文件
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
- 在具体的mapper.xml中声明开启
<!-- 该mapper操作Student -->
<mapper namespace="pers.qiu.StudentMapper">
<cache/>
</mapper>
- 实现序列化接口
class Student implements Serializable{
}
// 如果Student类中有其他类作为属性,则应该级联进行序列化。例如Student中有StudentCard对象作为属性:
class StudentCard implements Serializable{
}
缓存时机
Mybatis进行缓存的时机在session对象close时,也就是session.close()时。(与一级缓存不同,一级缓存自动存入缓存中)
禁用二级缓存
在mapper文件中使用cache标签,是将整个mapper中的所有方法开启二级缓存,但是有时一些方法我们需要禁用二级缓存。
扫描二维码关注公众号,回复:
13004379 查看本文章
<mapper namespace="">
<cache/>
<select id="xxx1" xxx>
xxx
</select>
<select id="xxx2" xxx useCache="false">
xxx
</select>
</mapper>
通过上述方法,xxx2方法关闭了二级缓存。而xxx1与其他未关闭方法都开启着二级缓存。
清理二级缓存
与一级缓存相同,使用commit方法清理缓存。