MyBatis(二六):缓存——缓存原理
首先来思考一下,在开启了二级缓存的情况下,一个用户查询数据经历的过程是什么样的。
我们看一下,下面这张图:
用户先去二级缓存中去寻找数据,如果找不到再去一级缓存寻找数据,如果还是找不到那么去数据库中进行查询。
我么具体来看一下:
@Test public void getUserById() { SqlSession sqlSession = MyBatisUtil.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.getUserById(10001); System.out.println(user); sqlSession.close(); System.out.println("========================================="); SqlSession sqlSession1 = MyBatisUtil.getSqlSession(); UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class); User user1 = userMapper1.getUserById(10001); System.out.println(user1); sqlSession1.close(); System.out.println("========================================="); SqlSession sqlSession2 = MyBatisUtil.getSqlSession(); UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class); User user2 = userMapper2.getUserById(10003); System.out.println(user2); System.out.println("========================================="); User user3 = userMapper2.getUserById(10003); System.out.println(user3); sqlSession2.close(); }