1、一级缓存
SqlSession sqlSession = SqlSessionUtils.getSqlSession();CacheMapper mapper = sqlSession.getMapper(CacheMapper.class);Emp emp1 = mapper.getEmpByEid(1);System.out.println(emp1);Emp emp2 = mapper.getEmpByEid(1);System.out.println(emp2);
可以看到只访问了一次数据库(因为只有一条sql语句记录)
SqlSession sqlSession = SqlSessionUtils.getSqlSession();CacheMapper mapper1 = sqlSession.getMapper(CacheMapper.class);CacheMapper mapper2 = sqlSession.getMapper(CacheMapper.class);Emp emp1 = mapper1.getEmpByEid(1);Emp emp2 = mapper2.getEmpByEid(1);System.out.println(emp1);System.out.println(emp2);
一样的结果
但是此情况下:
SqlSession sqlSession1 = SqlSessionUtils.getSqlSession();SqlSession sqlSession2 = SqlSessionUtils.getSqlSession();CacheMapper mapper = sqlSession1.getMapper(CacheMapper.class);Emp emp1 = mapper.getEmpByEid(1);CacheMapper mapper1 = sqlSession2.getMapper(CacheMapper.class);Emp emp2 = mapper1.getEmpByEid(1);System.out.println(emp1);System.out.println(emp2);
可以看到访问了2次数据库,因为我们创建了两个sqlSession
因此可以看到一级缓存的范围在同一个sqlSession下。
2、使一级缓存失效
在中间增加一个添加操作
SqlSession sqlSession = SqlSessionUtils.getSqlSession();CacheMapper mapper = sqlSession.getMapper(CacheMapper.class);Emp emp1 = mapper.getEmpByEid(1);System.out.println(emp1);int result = mapper.insertEmp(new Emp(null, "ab", 21, "女", "ab@qq.com"));System.out.println(result);Emp emp2 = mapper.getEmpByEid(1);System.out.println(emp2);
可以看到访问了三次,说明一级缓存失效了。
2、二级缓存
1)二级缓存的实现
(1)添加cache标签
(2)对应的实体类序列化
try {InputStream is = Resources.getResourceAsStream("mybatis-config.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);SqlSession sqlSession1 = sqlSessionFactory.openSession(true);CacheMapper mapper1 = sqlSession1.getMapper(CacheMapper.class);Emp emp1 = mapper1.getEmpByEid(1);System.out.println(emp1);sqlSession1.close();SqlSession sqlSession2 = sqlSessionFactory.openSession();CacheMapper mapper2 = sqlSession2.getMapper(CacheMapper.class);Emp emp2 = mapper2.getEmpByEid(1);System.out.println(emp2);} catch (IOException e) {e.printStackTrace();}}
一个SqlSessionFactory建立了sqlSession1和sqlSession2
注意当缺sqlSession1.close()或是sqlSession1.commit() 不会实现二级缓存,不满足条件c
2)、使二级缓存失效的情况:
3)、二级缓存的相关配置
3、缓存的查询顺序