2

求问 Mybatis 的缓存

 2 years ago
source link: https://www.v2ex.com/t/825687
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  Java

求问 Mybatis 的缓存

  daimubai · 1 天前 · 709 次点击

已经将一级缓存设置为了 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 条附言  ·  1 天前

总结:
Spring 中
1. mybatis 的一级缓存默认为 session ,但是只有在事务中缓存才会生效,也就是相同的两次查询只会执行一次
2. 如果碰到这种情况则是隔离级别导致的。修改为 read committed 即可。Spring 的隔离级别默认是和数据库一致的
如果不想修改数据库的隔离级别,则要在指定 Transactional 中指定 isolation

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK