MyBatis中的缓存就是将从数据库中查询出来的数据暂时记录,下次再有相同的查询就可以直接返回结果。
MyBatis的一级缓存针对的是SqlSession级别的,即同一个SqlSession执行查询后会将结果存放,下次再有相同的查询可以直接获取缓存数据。
一级缓存失效的四种情况:
MyBatis二级缓存是SqlSessionFactory级别的缓存,要想开启二级缓存必须满足以下几个条件:
cacheEnabled
为true。(默认为true所以不用手动设置)
标签。代表该映射文件开启二级缓存。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);
}
运行结果:
保存缓存数据时:
查询缓存时: