一、概述
Mybatis一级缓存的作用域是同一个SqlSession,在同一个SqlSession中执行两次相同的查询,第一次执行完毕后,Mybatis会将查询到的数据缓存起来(缓存到内存中), 第二次执行相同的查询时,会从缓存中取数据,不再进行数据库的查询,从而提高查询效率。默认情况下,Mybatis开启了一级换粗。
二、一级缓存(生效)案例演示
2.1、 CacheTest
@Test
public void test1() {UserMapper userMapper = sqlSession.getMapper(UserMapper.class);UserDO u1 = userMapper.getUserById(1);System.out.println("u1 = " + u1);System.out.println("===============");UserDO u2 = userMapper.getUserById(1);System.out.println("u2 = " + u2);
}
三、一级缓存(失效)案例(原因)演示
3.1、两次查询使用的不是同一个sqlSession
/*** mybatis的一级缓存失效的第一种原因:两次查询使用的不是同一个sqlSession*/
private static void m1() {SqlSession sqlSession1 = SqlSessionFactoryUtil.getInstance().openSession();SqlSession sqlSession2 = SqlSessionFactoryUtil.getInstance().openSession();UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class);UserDO u1 = userMapper1.getUserById(1);System.out.println(u1);System.out.println("=================");UserDO u2 = userMapper2.getUserById(1);System.out.println(u2);
}
3.2、两次查询之间有增删改的操作
/*** mybatis的一级缓存失效的第二种原因:两次查询之间有增删改的操作*/
private void m12() {UserMapper userMapper = sqlSession.getMapper(UserMapper.class);UserDO u1 = userMapper.getUserById(1);System.out.println(u1);int result = userMapper.delUserById(2);System.out.println("result = " + result);UserDO u2 = userMapper.getUserById(1);System.out.println(u2);
}
3.3、两次查询的查询条件不一样
/*** mybatis的一级缓存失效的第三种原因:两次查询的查询条件不一样*/
private void m13() {UserMapper userMapper = sqlSession.getMapper(UserMapper.class);UserDO u1 = userMapper.getUserById(1);System.out.println(u1);UserDO u2 = userMapper.getUserById(2);System.out.println(u2);
}