9、MyBatis缓存

9、MyBatis缓存

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

9.1、一级缓存

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

9、MyBatis缓存_第1张图片

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

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

9.2、二级缓存

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

  1. 核心配置文件中全局设置cacheEnabled为true。(默认为true所以不用手动设置)
  2. 在对应的Mapper文件中加入标签。代表该映射文件开启二级缓存。
  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、MyBatis缓存_第2张图片

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

保存缓存数据时:

9、MyBatis缓存_第3张图片

查询缓存时:

9、MyBatis缓存_第4张图片

你可能感兴趣的:(MyBatis,mybatis,缓存,java)