mybatis一级缓存详解

一级缓存是MyBatis的会话缓存,默认开启且不可关闭。它在同一个sqlSession内,对同一查询的二次调用将使用缓存数据。缓存存储在Executor的localCache中,采用CacheKey进行命中判断。当执行增删改操作或关闭sqlSession时,一级缓存会被清空。
摘要由CSDN通过智能技术生成
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(
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值