在mybatis中 分为一级缓存 二级缓存
一级缓存 sqlseesion级别的缓存
二级缓存 namespace级别的缓存
一级缓存是始终存在的
验证一级缓存的存在
@Test
public void deptCollectionEmpsTest(){
SqlSession session = MBUtils.getSession();
DeptMapper mapper = session.getMapper(DeptMapper.class);
Dept dept1 = mapper.selectDeptById(10);
System.out.println(dept1.getDname() +"---"+ dept1.getLoc());
MBUtils.closeSession();
//当sesson被关闭之后 此时一级缓存就失效了
session = MBUtils.getSession();
mapper = session.getMapper(DeptMapper.class);
Dept dept2 = mapper.selectDeptById(10);
System.out.println(dept2.getDname() +"---"+ dept2.getLoc());
}
缓存同步
@Test
public void deptCollectionEmpsTest(){
SqlSession session = MBUtils.getSession();
DeptMapper mapper = session.getMapper(DeptMapper.class);
Dept dept1 = mapper.selectDeptById(10);
System.out.println(dept1.getDname() +"---"+ dept1.getLoc());
dept1.setLoc("太原");
// 一级缓存失效 关闭session 执行更新操作
mapper.updateDept(dept1);
Dept dept2 = mapper.selectDeptById(10);
System.out.println(dept2.getDname() +"---"+ dept2.getLoc());
}
二级缓存默认是关闭
<!-- 开启二级缓存-->
<setting name="cacheEnabled" value="true"></setting>
在mapper文件中
<!-- 使用二级缓存-->
<cache/>
针对使用二级缓存的对象 必须进行序列化 实现Serializable
还可以针对单条sql语句来设置缓存
缓存的主要作用 : 提升查询效率
其他的缓存框架 ehcache 的使用
1.引入依赖
2.配置ehcache
<ehcache>
<!--
磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存
path:指定在硬盘上存储对象的路径
-->
<diskStore path="java.io.tmpdir" />
<!--
defaultCache:默认的缓存配置信息,如果不加特殊说明,则所有对象按照此配置项处理
maxElementsInMemory:设置了缓存的上限,最多存储多少个记录对象
eternal:代表对象是否永不过期
timeToIdleSeconds:最大的空闲时间
timeToLiveSeconds:最大的存活时间
overflowToDisk:是否允许对象被写入到磁盘
-->
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" />
<!--
cache:为指定名称的对象进行缓存的特殊配置
name:指定对象的完整名
-->
<cache name="org.zhang.pojo.Dept" maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" />
</ehcache>
在mybatis中使用ehcache
<cache type="org.mybatis.caches.ehcache.EhcacheCache" />