Mybatis一級快取和結合Spring Framework後失效的原始碼探究

碼猿手發表於2021-04-27

  1.在下面的案例中,執行兩次查詢控制檯只會輸出一次 SQL 查詢:

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/xxx?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true"/>
                <property name="username" value="xxx"/>
                <property name="password" value="xxx"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/hrh/mapper/PersonMapper.xml"/>
    </mappers>
</configuration>
PersonMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.hrh.mapper.PersonMapper">
    <resultMap id="BaseResultMap" type="com.hrh.bean.Person">
        <id column="id" property="id" jdbcType="BIGINT"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <result column="age" property="age" jdbcType="BIGINT"/>
    </resultMap>
    <sql id="Base_Column_List">
    id, name, age
    </sql>
    <select id="list" resultType="com.hrh.bean.Person">
        select
        <include refid="Base_Column_List"/>
        from tab_person
    </select>
</mapper>
public interface PersonMapper {
     List<Person> 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 存在一級快取導致的,下面 debug 探究下內部流程:

  (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);
  }

  

  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 <E> Object executeForMany(SqlSession sqlSession, Object[] args) {
    List<E> result;
    //獲取引數
    Object param = method.convertArgsToSqlCommandParam(args);
    //是否有分頁查詢
    if (method.hasRowBounds()) {
      RowBounds rowBounds = method.extractRowBounds(args);
      result = sqlSession.<E>selectList(command.getName(), param, rowBounds);
    } else {
      result = sqlSession.<E>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 <E> List<E> selectList(String statement, Object parameter) {
    return this.selectList(statement, parameter, RowBounds.DEFAULT);
  }
  public <E> List<E> 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();
    }
  }

 

  (5)接下來呼叫快取執行器的方法:CachingExecutor#query()

  public <E> List<E> 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 <E> List<E> 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<E> list = (List<E>) tcm.getObject(cache, key);
        if (list == null) {
          list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
          tcm.putObject(cache, key, list); // issue #578 and #116
        }
        return list;
      }
    }
    //沒有快取連線查詢
    return delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }

  (6)接下來執行 BaseExecutor#query():從下面可以看到將結果快取到 localCache 中了

  public <E> List<E> 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),且 <select> 的 flushCache=true 時清空快取
    if (queryStack == 0 && ms.isFlushCacheRequired()) {
      clearLocalCache();
    }
    List<E> list;
    try {
     //巢狀查詢層數+1
      queryStack++;
      //從localCache快取中獲取
      list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
      if (list != null) {
        handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
      } else {
        //連線查詢
        list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
      }
    } finally {
      queryStack--;
    }
    //下面是延遲載入邏輯
    if (queryStack == 0) {
      for (DeferredLoad deferredLoad : deferredLoads) {
        deferredLoad.load();
      }
      // issue #601
      deferredLoads.clear();
      if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
        // issue #482
        clearLocalCache();
      }
    }
    return list;
  }
  private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    List<E> list;
    //快取中新增佔位符
    localCache.putObject(key, EXECUTION_PLACEHOLDER);
    try {
      //連線查詢獲取到資料結果    
      list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
    } finally {
      //刪除佔位符
      localCache.removeObject(key);
    }
    //將結果快取起來
    localCache.putObject(key, list);
    //處理儲存過程
    if (ms.getStatementType() == StatementType.CALLABLE) {
      localOutputParameterCache.putObject(key, parameter);
    }
    return list;
  }

  2.但當 Spring Framework + Mybatis 時,情況就不一樣了,每次查詢都會連線資料庫查詢,控制檯都會列印 SQL 出來,如下案例:

@Service
public class PersonService  {
    @Autowired
    PersonMapper personMapper;

    public List<Person> getList() {
        personMapper.list();
        personMapper.list();
        return personMapper.list();
    }
}
@Configuration
@ComponentScan("com.hrh")
@MapperScan("com.hrh.mapper")
public class MyBatisConfig {
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource());
        factoryBean.setMapperLocations(resolveMapperLocations());
        return factoryBean;
    }

    public Resource[] resolveMapperLocations() {
        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        List<String> mapperLocations = new ArrayList<>();
        mapperLocations.add("classpath*:com/hrh/mapper/*Mapper*.xml");
        List<Resource> resources = new ArrayList();
        if (mapperLocations != null) {
            for (String mapperLocation : mapperLocations) {
                try {
                    Resource[] mappers = resourceResolver.getResources(mapperLocation);
                    resources.addAll(Arrays.asList(mappers));
                } catch (IOException e) {
                    // ignore
                }
            }
        }
        return resources.toArray(new Resource[resources.size()]);
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        driverManagerDataSource.setUsername("xxx");
        driverManagerDataSource.setPassword("xxx");
        driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/xxx?useUnicode=true&characterEncoding=utf-8&autoReconnect=true");
        return driverManagerDataSource;
    }
}
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyBatisConfig.class);
        PersonService bean = context.getBean(PersonService.class);
        bean.getList();

 

  下面debug進入的步驟跟上面的(1)、(2)、(3)是一致的,但第四步卻是進入 SqlSessionTemplate#selectList() 中【SqlSessionTemplatemybatis-spring-xx.jar的,上文的DefaultSqlSession是屬於mybatis-xx.jar的】:

  public <E> List<E> selectList(String statement, Object parameter) {
    return this.selectList(statement, parameter, RowBounds.DEFAULT);
  }

  接下來的 selectList() 會被方法攔截:method.invoke() 會執行到 DefaultSqlSession#selectList(),重新回到上文的第四步並且繼續下去,也就是在上文的(1)~(6)中插入了前後文,在其中做了關閉會話的操作;

  private class SqlSessionInterceptor implements InvocationHandler {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      //得到會話
      SqlSession sqlSession = getSqlSession(
          SqlSessionTemplate.this.sqlSessionFactory,
          SqlSessionTemplate.this.executorType,
          SqlSessionTemplate.this.exceptionTranslator);
      try {
        //執行方法查詢
        Object result = method.invoke(sqlSession, args);
        if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {
          // force commit even on non-dirty sessions because some databases require
          // a commit/rollback before calling close()
          sqlSession.commit(true);//在關閉會話前提交和回滾
        }
        return result;
        
      } catch (Throwable t) {//有異常丟擲異常並結束會話
        Throwable unwrapped = unwrapThrowable(t);
        if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
          // release the connection to avoid a deadlock if the translator is no loaded. See issue #22
          closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
          sqlSession = null;
          Throwable translated = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped);
          if (translated != null) {
            unwrapped = translated;
          }
        }
        throw unwrapped;
      } finally {
        //關閉會話
        if (sqlSession != null) {
          closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
        }
      }
    }
  }

 總結:

  Mybatis 的一級快取是會話級別的快取(單執行緒的,特別雞肋),Mybatis 每建立一個 SqlSession 會話物件,就表示開啟一次資料庫會話,在一次會話中,應用程式很可能在短時間內反覆執行相同的查詢語句,如果不對資料進行快取,則每查詢一次就要執行一次資料庫查詢,這就造成資料庫資源的浪費。又因為通過 SqlSession 執行的操作,實際上由 Executor 來完成資料庫操作的,所以在 Executor 中會建立一個簡單的快取,即一級快取;將每次的查詢結果快取起來,再次執行查詢的時候,會先查詢一級快取(預設開啟的),如果命中,則直接返回,否則再去查詢資料庫並放入快取中。

  一級快取的生命週期與 SqlSession 的生命週期相同,因此當 Mybatis 和 Spring Framework 的整合包中擴充套件了一個 SqlSessionTemplate 類(它是一個代理類,增強了查詢方法),所有的查詢經過 SqlSessionTemplate 代理攔截後再進入到 DefaultSqlSession#selectList() 中,結束查詢後把會話SqlSession 關了,所以導致了快取失效。

  那為什麼要這麼操作呢?

  原始的 Mybatis 有暴露 SqlSession 介面,因此有 close 方法暴露出來供你選擇使用,你可以選擇關與不關,但在 Mybatis 和 Spring Framework 的整合包中,SqlSession 是交給了 Spring Framework 管理的,沒有暴露出來,為了穩妥決定,直接給你關了。

相關文章