mybatis的缓存机制

在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" />
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

如我一般的人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值