1.MyBatis默认提供了SqlSession级别的一级缓存。同样的数据查询得到后会被缓存起来,下次再次访问时不必重新查询数据库
2.一级缓存测试
①有效的一级缓存测试
②失败的一级缓存测试 ※面试相关
[1]SQL语句或查询条件不同
[2]分属不同SqlSession对象
[3]查询前执行clearCache()
[4]提交事务
3.配置MyBatis自带二级缓存
①entity必须实现Serializable接口
public class Student implements Serializable{
private static final long serialVersionUID = 1L;
private Integer stuId;
private String stuName;
public Student() {}
public Integer getStuId() {
return stuId;
}
public void setStuId(Integer stuId) {
this.stuId = stuId;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
}
CREATE TABLE tbl_student (
stu_id INT NOT NULL AUTO_INCREMENT,
stu_name VARCHAR (200),
PRIMARY KEY (stu_id)
);
②开启二级缓存功能
mybatis-config.xml文件
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
③在XxxMapper.xml文件中配置二级缓存策略
<cache eviction="FIFO" flushInterval="60000" readOnly="true" size="512"/>
eviction:缓存策略
FIFO:First In First Out
LRU:Least Recently Used
flushInterval:缓存刷新时间间隔,时间是毫秒,检查是否存在过期对象
size:缓存中存储的对象个数
readOnly:是否只读
④二级缓存失效情况
[1]在查询select标签内设置useCache="false"
<select id="getStuById" parameterType="Integer" resultType="Student" useCache="false">
select stu_id stuId,stu_name stuName from tbl_student where stu_id=#{stuId}
</select>
[2]在执行增删改操作时刷新缓存
<update id="updateStu" parameterType="com.sirius.mybatis.entity.Student" flushCache="true">
update tbl_student set stu_name=#{stuName} where stu_id=#{stuId}
</update>
这是默认设置,通常不必修改
4.整合EHCache
①为什么要整合EHCache?
EHCache更专业
②操作
[1]添加jar包
ehcache-core-2.6.8.jar
mybatis-ehcache-1.0.3.jar
slf4j-api-1.6.1.jar
[2]加入EHCache自身配置文件ehcache.xml
<ehcache>
<diskStore path="D:/temp"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="20"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
</ehcache>
[3]开启EHCache缓存XxxMapper.xml文件中配置
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
[4]测试
5.MyBatis缓存原理
①MyBatis一级缓存基于org.apache.ibatis.cache.impl.PerpetualCache
[1]核心代码:private Map<Object, Object> cache = new HashMap<Object, Object>();
[2]主要方法:
(1)将数据放入缓存
public void putObject(Object key, Object value) {
cache.put(key, value);
}
(2)从缓存中获取数据
public Object getObject(Object key) {
return cache.get(key);
}
(3)将数据从缓存中删除
public Object removeObject(Object key) {
return cache.remove(key);
}
(4)清空缓存
public void clear() {
cache.clear();
}
[3]说明:一级缓存的作用域为Session级别,flush或close后缓存被释放
②MyBatis二级缓存与一级缓存机制相同,默认情况下同样采用PerpetualCache实现,但可以自定义存储源,如EHCache等。
org.mybatis.caches.ehcache.EhcacheCache