命名空间是mapper标签的一个属性
<mapper namespace="com.tt.spring.demo.dao.UserDao">
<cache />
</mapper>
命名空间在Mybatis
中会抽象成MappedStatement
不同的sqlSession使用的MappedStatement
实际是同一个,因为都是从全局的Configuration中获取的
private <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
try {
MappedStatement ms = configuration.getMappedStatement(statement);
return executor.query(ms, wrapCollection(parameter), rowBounds, handler);
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
不同的SqlSession都会创建一个新的Executor,这里执行CachingExecutor的query方法
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
throws SQLException {
// 从命名空间中拿到cache
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.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);
}
因此执行mappedStatement.getCache()
方法,都是从全局的命名空间中获取的cache,不同的sqlSession是共享的
由图可以看出,不同的sqlSession,在执行selectList命令时,都可以通过mappedStatement获取