1.mybatis中的缓存是在mybatis框架中的Executor中来实现的,我们来看一下Executor的继承图

2.通过以上类图我们可以发现Executor接口下有两大实现类BaseExecutor与CachingExecutor

(1)BaseExecutor(用来存储我们的一级缓存)

@Override
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; //会先去localCache中去查找我们的数据
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;
}

(2)CachingExecutor(是装饰器模式的实现,用来查询我们的二级缓存)

@Override
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
throws SQLException {
Cache cache = ms.getCache(); //在MappedStatement中去获取二级缓存的类型。
if (cache != null) {
flushCacheIfRequired(ms);
if (ms.isUseCache() && resultHandler == null) {
ensureNoOutParams(ms, boundSql);
@SuppressWarnings("unchecked")
List<E> list = (List<E>) tcm.getObject(cache, key); //通过tcm来查询缓存,而tcm是CachingExecutor中的变量TransactionalCacheManager
if (list == null) {
list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); //delegate为CachingExecutor中保存的BaseExecutor的引用,若二级缓存不存在回去调用BaseExecutor的方法。
tcm.putObject(cache, key, list); // issue #578 and #116
}
return list;
}
}

3.当我们开启二级缓存后Mybatis会使用CachingExecutor去装饰我们的BaseExecutor,所以会先查询二级缓存后再去查询一级缓存。

Configuration中的newExecutor方法
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的类型
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
executor = new SimpleExecutor(this, transaction);
}
if (cacheEnabled) { //如果二级缓存开启则使用CachingExecutor去装饰我们的executor;
executor = new CachingExecutor(executor);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}

4.一级缓存与二级缓存的作用范围

  (1)一级缓存(由于一级缓存是存在BaseExecutor中的,而Executor又作为创建SqlSession的参数,因此一级缓存具有和sqlsession一样的生命周期)

这是在SqlSessionFactory中调用openSession()中调用的方法
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
final Environment environment = configuration.getEnvironment();
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
final Executor executor = configuration.newExecutor(tx, execType); //新建一个Executor作为参数传给DefaultSqlSession
return new DefaultSqlSession(configuration, executor, autoCommit);
} catch (Exception e) {
closeTransaction(tx); // may have fetched a connection so lets call close()
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}

  (2)二级缓存(使用CachingExecutor来装饰)

//CachingExecutor中的query方法
@Override
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
throws SQLException {
Cache cache = ms.getCache(); //由此可见我们的二级缓存并不是储存在CachingExecutor中的,而是从MappedStatement中去获取。因此mybatis的二级缓存的生命周期为mapper级别的
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);
}

    

mybatis一级缓存与二级缓存的原理的更多相关文章

  1. Mybatis 一级缓存和二级缓存原理区别 (图文详解)

    Java面试经常问到Mybatis一级缓存和二级缓存,今天就给大家重点详解Mybatis一级缓存和二级缓存原理与区别@mikechen Mybatis缓存 缓存就是内存中的数据,常常来自对数据库查询结 ...

  2. MyBatis 延迟加载,一级缓存,二级缓存设置

    什么是延迟加载 resultMap中的association和collection标签具有延迟加载的功能. 延迟加载的意思是说,在关联查询时,利用延迟加载,先加载主信息.使用关联信息时再去加载关联信息 ...

  3. 9.Mybatis一级缓存和二级缓存

    所谓的缓存呢?其实原理很简单,就是在保证你查询的数据是正确的情况下,没有去查数据库,而是直接查找的内存,这样做有利于缓解数据库的压力,提高数据库的性能,Mybatis中有提供一级缓存和二级缓存. 学习 ...

  4. 八 mybatis查询缓存(一级缓存,二级缓存)和ehcache整合

    1       查询缓存 1.1     什么是查询缓存 mybatis提供查询缓存,用于减轻数据压力,提高数据库性能. mybaits提供一级缓存,和二级缓存.

  5. mybatis 详解(九)------ 一级缓存、二级缓存

    上一章节,我们讲解了通过mybatis的懒加载来提高查询效率,那么除了懒加载,还有什么方法能提高查询效率呢?这就是我们本章讲的缓存. mybatis 为我们提供了一级缓存和二级缓存,可以通过下图来理解 ...

  6. Mybatis第八篇【一级缓存、二级缓存、与ehcache整合】

    Mybatis缓存 缓存的意义 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题. myba ...

  7. MyBatis 一级缓存,二级缓存,延迟加载设置

       1  什么是延迟加载  resultMap中的association和collection标签具有延迟加载的功能. 延迟加载的意思是说,在关联查询时,利用延迟加载,先加载主信息.使用关联信息时再 ...

  8. mybatis的延迟加载、一级缓存、二级缓存

    mybatis的延迟加载.一级缓存.二级缓存 mybatis是什么? mybatis是一个持久层框架,是apache下的开源项目,前身是itbatis,是一个不完全的ORM框架,mybatis提供输入 ...

  9. 深入理解MyBatis中的一级缓存与二级缓存

    http://blog.csdn.net/weixin_36380516/article/details/73194758   先说缓存,合理使用缓存是优化中最常见的,将从数据库中查询出来的数据放入缓 ...

随机推荐

  1. 使screen支持滚动

    在Linux中,常用的串口工具有minicom和screen,minicom可能使用得比较多,但是我比较喜欢screen,因为它的输出是彩色的,更舒服.更能突出重点. 使用screen来打开串口也非常 ...

  2. golang之递归

    翠花,上代码 package main import ( "fmt" "time" ) /* 递归原则,一个大问题分解成相似的小问题 定义好出口条件,否则死循环 ...

  3. PHPStorm 忽略 node_modules 目录

    如果项目中包含 node_modules 目录,会使 PHPStorm 卡得很慢, 原因:PHPStorm 在进行大量的扫描工作. 解决:忽略它 原文地址:https://segmentfault.c ...

  4. 统计学中z分布、t分布、F分布及χ^2分布

    Z就是正态分布,X^2分布是一个正态分布的平方,t分布是一个正态分布除以(一个X^2分布除以它的自由度然后开根号),F分布是两个卡方分布分布除以他们各自的自由度再相除 比如X是一个Z分布,Y(n)=X ...

  5. context:propertyPlaceholder

    Activates replacement of ${...} placeholders by registering a PropertySourcesPlaceholderConfigurer w ...

  6. Redis-3.2.0集群配置(redis cluster)

    版本:redis-3.0.5 redis-3.2.0  redis-3.2.9  redis-4.0.11 参考:http://redis.io/topics/cluster-tutorial. 目录 ...

  7. 企业搜索引擎开发之连接器connector(十八)

    创建并启动连接器实例之后,连接器就会基于Http协议向指定的数据接收服务器发送xmlfeed格式数据,我们可以通过配置http代理服务器抓取当前基于http协议格式的数据(或者也可以通过其他网络抓包工 ...

  8. [label][Chrome-Extension] How to start Chrome Extension's development

    Firstly , you should read these two pages.  https://developer.chrome.com/extensions/overview https:/ ...

  9. 7.使用ZookeeperNet进行CDU操作参数详解

    一.创建,删除,更新 1. zkCli.sh 中使用命令执行. 2. 学会查看api文档 zookeeper C# driver 官方文档,文档是java代码的. http://zookeeper.a ...

  10. Github注册及心得

    注册Github流程: 1.搜索www.github.com 2.有两个按钮sign up(注册).sign in(登入)