Mybatis一级缓存和结合Spring Framework后失效的源码探究

  1.在下面的案例中,执行两次查询控制台只会输出一次 SQL 查询:

mybatis-config.xml




    
        
            
            
                
                
                
                
            
        
    
    
        
    
PersonMapper.xml



    
        
        
        
    
    
    id, name, age
    
    
public interface PersonMapper {
     List list();
}
String resource = "mybatis-config2.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory =
                new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();//开启会话
        PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
        mapper.list();
        mapper.list();

Mybatis一级缓存和结合Spring Framework后失效的源码探究_第1张图片

  之所以会出现这种情况,是因为 Mybatis 存在一级缓存导致的,下面 debug 探究下内部流程:

Mybatis一级缓存和结合Spring Framework后失效的源码探究_第2张图片

  (1)mapper.list() 会进入 MapperProxy#invoke():参数proxy是一个代理对象(每个 Mapper 接口都会被转换成一个代理对象),里面包含会话 sqlSession、接口信息、方法信息;method是目标方法(当前执行的方法),它里面包含了所属的哪个类(接口)、方法名、返回类型(List、Map、void 或其他)、参数类型等;args是参数;

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, args);
      } else if (isDefaultMethod(method)) {
        return invokeDefaultMethod(proxy, method, args);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
    //从方法缓存methodCache中获取到方法的信息:比如方法名、类型(select、update等)、返回类型
    //如果获取中没有MapperMethod,则创建一个并放入methodCache中
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    //执行查询SQL并返回结果
    return mapperMethod.execute(sqlSession, args);
  }

  Mybatis一级缓存和结合Spring Framework后失效的源码探究_第3张图片

  cacheMapperMethod:MapperMethod 包含方法名、类型(select、update等)、返回类型等信息

private MapperMethod cachedMapperMethod(Method method) {
    //缓存中获取
    MapperMethod mapperMethod = methodCache.get(method);
    //没有则创建一个对象并放入缓存中供下次方便取用
    if (mapperMethod == null) {
      mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
      methodCache.put(method, mapperMethod);
    }
    return mapperMethod;
  }

  (2)MapperMethod#execute()根据 SQL 类型进入不同的查询方法

public Object execute(SqlSession sqlSession, Object[] args) {
    //返回结果
    Object result;
    //判断语句类型
    switch (command.getType()) {
      case INSERT: {//插入语句
      Object param = method.convertArgsToSqlCommandParam(args);
        result = rowCountResult(sqlSession.insert(command.getName(), param));
        break;
      }
      case UPDATE: {//更新语句
        Object param = method.convertArgsToSqlCommandParam(args);
        result = rowCountResult(sqlSession.update(command.getName(), param));
        break;
      }
      case DELETE: {//删除语句
        Object param = method.convertArgsToSqlCommandParam(args);
        result = rowCountResult(sqlSession.delete(command.getName(), param));
        break;
      }
      case SELECT://查询语句
        //返回空的查询
        if (method.returnsVoid() && method.hasResultHandler()) {
          executeWithResultHandler(sqlSession, args);
          result = null;
          //返回List的查询
        } else if (method.returnsMany()) {
          result = executeForMany(sqlSession, args);
          //返回Map的查询
        } else if (method.returnsMap()) {
          result = executeForMap(sqlSession, args);
          //返回游标的查询
        } else if (method.returnsCursor()) {
          result = executeForCursor(sqlSession, args);
        } else {
          Object param = method.convertArgsToSqlCommandParam(args);
          result = sqlSession.selectOne(command.getName(), param);
        }
        break;
      case FLUSH:
        result = sqlSession.flushStatements();
        break;
      default:
        throw new BindingException("Unknown execution method for: " + command.getName());
    }
    if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
      throw new BindingException("Mapper method '" + command.getName() 
          + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
    }
    return result;
  }

  (3)上面的案例是 select 语句,返回结果是List集合,所以进入 MapperMethod#executeForMany():

private  Object executeForMany(SqlSession sqlSession, Object[] args) {
    List result;
    //获取参数
    Object param = method.convertArgsToSqlCommandParam(args);
    //是否有分页查询
    if (method.hasRowBounds()) {
      RowBounds rowBounds = method.extractRowBounds(args);
      result = sqlSession.selectList(command.getName(), param, rowBounds);
    } else {
      result = sqlSession.selectList(command.getName(), param);
    }
    // issue #510 Collections & arrays support
    //如果list中的泛型跟结果类型不一致,进行转换
    if (!method.getReturnType().isAssignableFrom(result.getClass())) {
      if (method.getReturnType().isArray()) {
        return convertToArray(result);
      } else {
        return convertToDeclaredCollection(sqlSession.getConfiguration(), result);
      }
    }
    return result;
  }

  (4)selectList执行了DefaultSqlSession#selectList():

 public  List selectList(String statement, Object parameter) {
    return this.selectList(statement, parameter, RowBounds.DEFAULT);
  }
public  List selectList(String statement, Object parameter, RowBounds rowBounds) {
    try {
      //SQL执行的信息:resource(xxMapper.xml)、id、sql、返回类型等
      MappedStatement ms = configuration.getMappedStatement(statement);
      //执行查询
      return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

Mybatis一级缓存和结合Spring Framework后失效的源码探究_第4张图片

  (5)接下来调用缓存执行器的方法:CachingExecutor#query()

public  List query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
    //获取到执行SQL
    BoundSql boundSql = ms.getBoundSql(parameterObject);
    //将SQL包装成一个缓存对对象,该对象和结果集组成键值对存储到缓存中,方便下次直接从缓存中拿而不需要再次查询
    //createCacheKey:调用BaseExecutor#createCacheKey
    CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
    return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }
public  List query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
      throws SQLException {
    //获取缓存
    Cache cache = ms.getCache();
    if (cache != null) {
      flushCacheIfRequired(ms);
      if (ms.isUseCache() && resultHandler == null) {
        ensureNoOutParams(ms, boundSql);
        @SuppressWarnings("unchecked")
        List list = (List) tcm.getObject(cache, key);
        if (list == null) {
          list = delegate. query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
          tcm.putObject(cache, key, list); // issue #578 and #116
        }
        return list;
      }
    }
    //没有缓存连接查询
    return delegate. query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }

  (6)接下来执行 BaseExecutor#query():从下面可以看到将结果缓存到localCache 中了

public  List query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
    if (closed) {
      throw new ExecutorException("Executor was closed.");
    }
    //如果不是嵌套查询(默认为0),且