博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mybatis学习及原理解析(三)
阅读量:3904 次
发布时间:2019-05-23

本文共 2233 字,大约阅读时间需要 7 分钟。

关于mybatis的二级缓存

在配置文件中开启二级缓存

第一次测试

@Test    public void firstLevelCache() {
//第一次查询id为1的用户 User user1 = userMapper.findUserById(1); User user2 = userMapper.findUserById(1); System.out.println(user1 == user2); } @Test public void secondLevelCache() {
SqlSession sqlSession1 = sqlSessionFactory.openSession(); SqlSession sqlSession2 = sqlSessionFactory.openSession(); SqlSession sqlSession3 = sqlSessionFactory.openSession(); IUserMapper mapper1 = sqlSession1.getMapper(IUserMapper.class); IUserMapper mapper2 = sqlSession2.getMapper(IUserMapper.class); IUserMapper mapper3 = sqlSession3.getMapper(IUserMapper.class); User user1 = mapper1.findUserById(1); sqlSession1.close(); User user2 = mapper2.findUserById(1); User user3 = mapper3.findUserById(1); System.out.println(user1 == user2); }

写了两个测试方法,

  1. 第一个测试方法用同一个sqlSession执行两次findUserById,发现,第一次调用,执行了sql语句,第二次没有执行sql语句,打印结果为true
  2. 第二个测试方法测试二级缓存,两次调用findUserById,第一次调用,执行了sql语句,第二次没有执行sql语句,打印结果为flase,注:二级缓存实体类需要实现序列化接口

原因

一级缓存保存的是查询的对象

二级缓存只保存查询出的值

第二次测试

@Test    public void secondLevelCache() {
SqlSession sqlSession1 = sqlSessionFactory.openSession(); SqlSession sqlSession2 = sqlSessionFactory.openSession(); SqlSession sqlSession3 = sqlSessionFactory.openSession(); IUserMapper mapper1 = sqlSession1.getMapper(IUserMapper.class); IUserMapper mapper2 = sqlSession2.getMapper(IUserMapper.class); IUserMapper mapper3 = sqlSession3.getMapper(IUserMapper.class); User user1 = mapper1.findUserById(1); sqlSession1.close(); User user = new User(); user.setId(0); user.setUsername("zhangsan"); mapper3.updateUser(user); sqlSession3.commit(); User user2 = mapper2.findUserById(1); System.out.println(user1 == user2); }

可以发现在执行修改操作之后,mybatis会清空二级缓存,因此会执行两次查询数据库的操作

useCache和flushCache

useCache:单个标签使用,表示可以单独开关二级缓存

flushCache: 表示刷新缓存,默认为true,在执行增删改操作后清空二级缓存,false,可能导致脏读

myBatis自带的二级缓存PerpetualCache

问题:无法实现分布式缓存

解决方法

在这里插入图片描述
使用mybatis提供的redis缓存

//依赖        
org.mybatis.caches
mybatis-redis
1.0.0-beta2

转载地址:http://namen.baihongyu.com/

你可能感兴趣的文章
Python List Operation
查看>>
python auto-increment
查看>>
Python List Comprehensions
查看>>
Python 递归 list不正确
查看>>
Python copy a list
查看>>
Iteration Vs Recursion Java
查看>>
What are some of the differences between using recursion to solve a problem versus using iteration?
查看>>
subsets
查看>>
Python Nested List Operation
查看>>
Python Binary Search
查看>>
How to append list to second list
查看>>
Write a program to print all permutations of a given string
查看>>
递归回溯
查看>>
穷举递归和回溯算法终结篇
查看>>
Exhaustive recursion and backtracking
查看>>
递归算法的时间复杂度终结篇
查看>>
全排列算法的递归与非递归实现
查看>>
Python Division and Remainders
查看>>
Python Division //
查看>>
BinarySearch
查看>>