9、MyBatis缓存

9、MyBatis缓存

MyBatis中的缓存就是将从数据库中查询出来的数据暂时记录,下次再有相同的查询就可以直接返回结果。

9.1、一级缓存

MyBatis的一级缓存针对的是SqlSession级别的,即同一个SqlSession执行查询后会将结果存放,下次再有相同的查询可以直接获取缓存数据。

在这里插入图片描述

一级缓存失效的四种情况:

  • 不同SqlSession对应不同的一级缓存。
  • 同一个SqlSession但是查询语句不同。
  • 两次查询之间执行了增删改任意操作。
  • 手动清空SqlSession缓存。

9.2、二级缓存

MyBatis二级缓存是SqlSessionFactory级别的缓存,要想开启二级缓存必须满足以下几个条件:

  1. 核心配置文件中全局设置cacheEnabled为true。(默认为true所以不用手动设置)
  2. 在对应的Mapper文件中加入<cache/>标签。代表该映射文件开启二级缓存。
  3. 二级缓存只有在SqlSession关闭或者手动提交后才有效。
  4. 查询出来的数据对应的实体类必须实现Serializable接口。
/**
 * Student selectOneById(@Param("sId") Integer sId);
 */
@Test
public void selectOneById() throws Exception {
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
    SqlSessionFactory sqlSessionFactory = factoryBuilder.build(is);
    SqlSession sqlSession1 = sqlSessionFactory.openSession(true);
    SqlSession sqlSession2 = sqlSessionFactory.openSession(true);
    StudentMapper mapper1 = sqlSession1.getMapper(StudentMapper.class);
    Student student1 = mapper1.selectOneById(1);
    System.out.println("第一次查询---->"+student1);
    sqlSession1.commit();
    StudentMapper mapper2 = sqlSession2.getMapper(StudentMapper.class);
    Student student2 = mapper2.selectOneById(1);
    System.out.println("第二次查询---->"+student2);
}

运行结果:

在这里插入图片描述

9.3、一级缓存和二级缓存的关系

保存缓存数据时:

在这里插入图片描述

查询缓存时:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值