mybatis一级缓存失效

在测试类中调用 mapper的selectOne() 方法,缓存失效,还是执行了10次查询


    @Test
    public void test_mybatis_plus_cache(){
       // 循环执行 selectOne()
        for (int i = 0; i < 10; i++) {
            sequenceMapper.selectOne(Wrappers.<Sequence>lambdaQuery().eq(Sequence::getType,1));
        }
    }

断点调试时 每次的 SqlSession 对象都是同一个 并且每次生成的 CacheKey 对象都是相同的

第一次

  • 这是第一次获取到的 SqlSession 对象

    img

  • 这是第一次生成的cacheKey

    img

第二次

  • 这是第二次获取到的 SqlSession 对象

    img

  • 这是第二次生成的cacheKey

    img

根据网上查询到的资料来看 sqlSession 和 Cachekey 一样应该第二次走缓存的 但是并没有

失效的位置

img

这里内部清除了 localCache中的缓存

    // 这里是最终调用清除缓存的代码
    @Override
  public void close(boolean forceRollback) {
    try {
      try {
        rollback(forceRollback);
      } finally {
        if (transaction != null) {
          transaction.close();
        }
      }
    } catch (SQLException e) {
      // Ignore. There's nothing that can be done at this point.
      log.warn("Unexpected exception on closing transaction.  Cause: " + e);
    } finally {
      // finally块中清除了 localCache 中的缓存
      transaction = null;
      deferredLoads = null;
      localCache = null;
      localOutputParameterCache = null;
      closed = true;
    }
  }

请问各位 如果按照这种逻辑走的话 一级缓存不是能生效的 我应该怎样才能使用到一级缓存呢?

在spring对一级缓存的设计就是这样的,当然在关闭session里面可以看到有个从事务管理器里获取session的操作,也就是当前查询如果开启事务那么会使用到一级缓存。

img

有没有可能是你的缓存没配置好