1.mybatis一级缓存
一级缓存: sqlSession缓存 [会话缓存]。默认开启,用户不能关闭(有方法让其失效)。通过同一个sqlSession调用同一个查询方法两次,第二次查询走的缓存。
下面我们就看看一级缓存怎么保存的?
在创建sqlSession的时候会创建Executor
BaseExecutor里有个属性localCache就是保存一级缓存内容的
public abstract class BaseExecutor implements Executor {
protected PerpetualCache localCache;
protected PerpetualCache localOutputParameterCache;
protected Configuration configuration;
打开看PerpetualCache类,看cache熟悉,其实就是个map
public class PerpetualCache implements Cache {
private final String id;
private Map<Object, Object> cache = new HashMap<Object, Object>();
接下来看看是怎么判断缓存命中的?
首先看看在BaseExecutor.query()方法在查询时先生成cachekey
@Override
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
BoundSql boundSql = ms.getBoundSql(parameter);
CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);
return query(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
cachekey怎么生成的?
@Override
public CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql) {
if (closed) {
throw new ExecutorException("Executor was closed.");
}
CacheKey cacheKey = new CacheKey();
cacheKey.update(ms.getId());//statmentid
cacheKey.update(rowBounds.getOffset());//默认是0
cacheKey.update(rowBounds.getLimit(