mybatis cachedEnable 配置是干什么的

官方文档:https://mybatis.org/mybatis-3/zh/configuration.html
因为读官方文档的配置,觉得有歧义,所以看了下源码;

结论:cachedEnable这个开关实际上控制的上创建executor(用来处理sql的)的类型,创建的executor取决于defaultExecutorType默认是SimpleExecutor这个类是没有二级缓存功能的,如果cachedEnable是true(默认),就会使用CachingExecutor对SimpleExecutor包装。CachingExecutor这个是具有二级缓存功能的。

   public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
        // 获得执行器类型
        executorType = executorType == null ? defaultExecutorType : executorType; // 使用默认
        executorType = executorType == null ? ExecutorType.SIMPLE : executorType; // 使用 ExecutorType.SIMPLE
        // 创建对应实现的 Executor 对象
        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);
        }
        // 如果开启缓存,创建 CachingExecutor 对象,进行包装
        if (cacheEnabled) {
            executor = new CachingExecutor(executor);
        }
        // 应用插件
        executor = (Executor) interceptorChain.pluginAll(executor);
        return executor;
    }

所以cachedEnable=false二级缓存就被关闭了,但是cachedEnable=true仅仅是使用了CachingExecutor,不能代表使用了二级缓存,因为CachingExecutor使用了Cache对象缓存数据,只有在Mapper中配置<cache/>标签,解析的时候才会有Cache对象,否则还是不会用到二级缓存的。

(二级坑比较多,用的人也很少)

public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
            throws SQLException {

        Cache cache = ms.getCache();
        //cache不是空才会走这里
        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);
    }

个人理解,如有问题欢迎指正。

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值