1.进入SqlSeesion的实现类DefaultSqlSession的selectList()方法
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
List var5;
try {
MappedStatement ms = this.configuration.getMappedStatement(statement);
// 这里的执行executor实现类是CachingExecutor,不是BaseExecutor,只要开启二级缓存openSession时创建的SqlSession中的Executor就为CachingExecutor。
var5 = this.executor.query(ms, this.wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
} catch (Exception var9) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + var9, var9);
} finally {
ErrorContext.instance().reset();
}
return var5;
}
2.进入CachingExecutor中的query方法。
// BaseExecutor
private final Executor delegate;
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
// 从 MappedStatement 中获取 Cache,注意这里的 Cache 是从MappedStatement中获取的 // 也就是我们上面解析Mapper中<cache/>标签中创建的,它保存在Configration中 // 我们在上面解析blog.xml时分析过每一个MappedStatement都有一个Cache对象,就是这里
Cache cache = ms.getCache();
// 如果配置文件中没有配置 <cache>,则 cache 为空
if (cache != null) {
//如果需要刷新缓存的话就刷新:flushCache="true"
this.flushCacheIfRequired(ms);
// 当前查询标签UseCache属性为true且无指定自定义resultHandler结果处理器时才走二级缓存.
if (ms.isUseCache() && resultHandler == null) {
this.ensureNoOutParams(ms, parameterObject, boundSql);
// 访问二级缓存
List<E> list = (List)this.tcm.getObject(cache, key);
// 缓存未命中
if (list == null) {
// 如果没有值,则执行查询走BaseExecutor执行器,这个查询实际也是先走一级缓存查询,一级缓存也没有的 话,则进行DB查询
list = this.delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
// 缓存查询结果
this.tcm.putObject(cache, key, list);
}
return list;
}
}
return this.delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
结论:如果二级缓存开启,且存在,则二级缓存在一级缓存之前生效。