Users often query the data in the cache (memory), users do not need to query data (relational database data files) from the disk query, the query from the cache to improve query efficiency, solve the problem of high-performance concurrent systems .
1.2 mybatis persistence cache
mybatis provide a cache and secondary cache
mybatis level cache is a SqlSession level, sqlsession only access their own data cache, secondary cache across sqlSession, a mapper level caching for mapper level caching different sqlsession it can be shared.
Second, the cache
2.1 Principle
The first issues a SQL query, the results of an SQL query sqlsession buffer write, the data structure is a map used by the cache
key: hashcode + sql + sql + input parameters an output parameter (the unique identification sql)
value: User Information
With a sqlsession make the same sql again, it does not take away from the cache database. If the middle appeared twice commit operation (modify, add, delete), a buffer area in this sqlsession all empty, go to the next cache can not find it from a database query, the query from the database to re-write cache.
Start every query cache query:
If the query cache to cache data will be returned directly.
If you can not find the cache from a database query:
2.2 cache configuration
mybatis default support level cache requires no configuration.
Note: After mybatis carried mapper agent development and integration of spring, do not support the cache, mybatis integration and spring, spring in accordance with the template mapper mapper to generate a proxy object, the template close sqlsession in the final reunification.
Cache test
//一级缓存
@Test
public void testCache1() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//第一次查询用户id为1的用户
User user = userMapper.findUserById(1);
System.out.println(user);
//中间修改用户要清空缓存,目的防止查询出脏数据
/*user.setUsername("测试用户2");
userMapper.updateUser(user);
sqlSession.commit();*/
//第二次查询用户id为1的用户
User user2 = userMapper.findUserById(1);
System.out.println(user2);
sqlSession.close();
}