在创建SqlSession时,根据mybatis配置为SqlSession生成一个执行器Executor,通过SqlSession的getMapper获取代理对象,执行查询方法时,实际上去调用Executor的query去进行。Executor接口有两个比较重要的实现CachingExecutor和BaseExecutor,CachingExecutor拥有一个被代理的BaseExecutor属性,CachingExecutor有一个作用就是执行BaseExecutor之前,可以进行二级缓存使用。在使用默认的settings时,SqlSession在创建时会生成CachingExecutor对象。
一级缓存:是基于SqlSession级别的缓存,也是本地缓存(存在于应用程序内存中)。是通过BaseExecutor的PerpetualCache去实现的,Executor是SqlSession的属性,生命周期与SqlSession,随着SqlSession的关闭而消失。
二级缓存:是基于Configuration的缓存,是全局的缓存,可以通过实现Cache接口去实现。是通过CachingExecutor的query时,去获取MappedStatement的Cache去实现缓存的,而MappedStatement的Cache实际上引用的Configuration的Map<String, Cache> caches属性,在解析Mapper.xml时已经确定。
通过代码来看一下
Executor的生成:
cacheEnabled对应的是<setting name="cacheEnabled">默认值是true,Executor在使用默认配置时使用的是代理对象CachingExecutor。
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
executor = new SimpleExecutor(this, transaction);
}
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
SqlSession执行查询方法selectList
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
try {
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();
}
}
CachingExecutor的查询query
CacheKey用于生成每次查询的唯一对象,ms.getCache()用于获取MappedStatement对应的缓存,也是我们常说的二级缓存,Configuration为每一个namespace都分配一个缓存对象(需要配置<cache>标签),delegate实际被代理的BaseExecutor对象,执行BaseExecutor的查询之前,会从二级缓存(<sql >必须要开启缓存)中去获取对应的查询结果,如果没有则将添加到缓存中。
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
BoundSql boundSql = ms.getBoundSql(parameterObject);
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);
}
BaseExecutor的查询query
localCache是BaseExecutor的一个PerpetualCache,其实就是Map<Object, Object>,就是所谓的一级缓存,queryFromDatabase则是查询并添加到二级缓存。doQuery是一个抽象的方法,这里使用了模板模式,BaseExecutor定义了在查询之前需要进行缓存这一动作,doQuery则由子类去实现的具体方法。
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.");
}
if (queryStack == 0 && ms.isFlushCacheRequired()) {
clearLocalCache();
}
List<E> list;
try {
queryStack++;
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;
}
通过分析源码我们可以很清楚了发现,如果配置了二级缓存,那么一级缓存就会失效。知道了缓存实现机制,那么也需要知道缓存什么时候被清空,在执行CacheingExecutor的update(insert|update|delete 时触发)和BaseExecutor的update方法时,会更新缓存。
这里以CacheingExecutor的代码为例进行说明,BaseExecutor机制一样。flushCacheIfRequired方法用来刷新缓存。
public int update(MappedStatement ms, Object parameterObject) throws SQLException {
flushCacheIfRequired(ms);
return delegate.update(ms, parameterObject);
}