已经将一级缓存设置为了 statement ,关闭了二级缓存
mybatis:
configuration:
cache-enabled: false
local-cache-scope: statement
测试
@GetMapping("/test")
@Transactional
public User test() throws InterruptedException {
User user = userMapper.selectById(1);
System.out.println(user);
TimeUnit.SECONDS.sleep(5);
User user2 = userMapper.selectById(1);
System.out.println(user2);
return user2;
}
疑问
2022-01-01 19:33:18.320 DEBUG 49182 --- [nio-8000-exec-4] com.ding.mapper.UserMapper.selectById : ==> Preparing: SELECT * FROM `user` WHERE id = ?
2022-01-01 19:33:18.321 DEBUG 49182 --- [nio-8000-exec-4] com.ding.mapper.UserMapper.selectById : ==> Parameters: 1(Integer)
2022-01-01 19:33:18.322 DEBUG 49182 --- [nio-8000-exec-4] com.ding.mapper.UserMapper.selectById : <== Total: 1
User(id=1, username=test, password=222, phone=)
2022-01-01 19:33:23.327 DEBUG 49182 --- [nio-8000-exec-4] com.ding.mapper.UserMapper.selectById : ==> Preparing: SELECT * FROM `user` WHERE id = ?
2022-01-01 19:33:23.327 DEBUG 49182 --- [nio-8000-exec-4] com.ding.mapper.UserMapper.selectById : ==> Parameters: 1(Integer)
2022-01-01 19:33:23.328 DEBUG 49182 --- [nio-8000-exec-4] com.ding.mapper.UserMapper.selectById : <== Total: 0
User(id=1, username=test, password=222, phone=)
日志是打印了两遍 sql ,在休眠的 5 秒前我已经在数据库把这条数据清空了,但是第二次执行的结果返回的还是和第一次一样
1
daimubai OP 这应该不是 Mybatis 缓存作的怪吧,如果缓存生效的话第二个 sql 应该不会执行才对。
但是我把事务去掉就可以了,如果非要加事务呢,求大佬指点 |
2
az467 2022-01-01 19:44:50 +08:00 1
db 隔离级别改为 read committed
|
3
daimubai OP |
5
potatowish 2022-01-02 09:57:12 +08:00 via iPhone
一级缓存是 sqlsession 级别的缓存,每次操作数据库会构造不同的 sqlsession 对象,缓存互不影响。
开启事务后,同一个事务中的数据库访问会复用 sqlsession ,所以会使用同一个缓存 |