MyBatis是常见的Java数据库访问层框架。在平常工做中,开发人员多数状况下是使用MyBatis的默认缓存配置,可是MyBatis缓存机制有一些不足之处,在使用中容易引发脏数据,造成一些潜在的隐患。我的在业务开发中也处理过一些因为MyBatis缓存引起的开发问题,带着我的的兴趣,但愿从应用及源码的角度为读者梳理MyBatis缓存机制。git
本次分析中涉及到的代码和数据库表均放在GitHub上,地址: mybatis-cache-demo 。github
本文按照如下顺序展开。算法
在应用运行过程当中,咱们有可能在一次数据库会话中,执行屡次查询条件彻底相同的SQL,MyBatis提供了一级缓存的方案优化这部分场景,若是是相同的SQL语句,会优先命中一级缓存,避免直接对数据库进行查询,提升性能。具体执行过程以下图所示。sql
每一个SqlSession中持有了Executor,每一个Executor中有一个LocalCache。当用户发起查询时,MyBatis根据当前执行的语句生成MappedStatement
,在Local Cache进行查询,若是缓存命中的话,直接返回结果给用户,若是缓存没有命中的话,查询数据库,结果写入Local Cache
,最后返回结果给用户。具体实现类的类关系图以下图所示。数据库
咱们来看看如何使用MyBatis一级缓存。开发者只需在MyBatis的配置文件中,添加以下语句,就可使用一级缓存。共有两个选项,SESSION
或者STATEMENT
,默认是SESSION
级别,即在一个MyBatis会话中执行的全部语句,都会共享这一个缓存。一种是STATEMENT
级别,能够理解为缓存只对当前执行的这一个Statement
有效。缓存
<setting name="localCacheScope" value="SESSION"/>
复制代码
接下来经过实验,了解MyBatis一级缓存的效果,每一个单元测试后都请恢复被修改的数据。安全
首先是建立示例表student,建立对应的POJO类和增改的方法,具体能够在entity包和mapper包中查看。bash
CREATE TABLE `student` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(200) COLLATE utf8_bin DEFAULT NULL,
`age` tinyint(3) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
复制代码
在如下实验中,id为1的学生名称是凯伦。session
开启一级缓存,范围为会话级别,调用三次getStudentById
,代码以下所示:mybatis
public void getStudentById() throws Exception {
SqlSession sqlSession = factory.openSession(true); // 自动提交事务
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
System.out.println(studentMapper.getStudentById(1));
System.out.println(studentMapper.getStudentById(1));
System.out.println(studentMapper.getStudentById(1));
}
复制代码
执行结果:
咱们能够看到,只有第一次真正查询了数据库,后续的查询使用了一级缓存。
增长了对数据库的修改操做,验证在一次数据库会话中,若是对数据库发生了修改操做,一级缓存是否会失效。
@Test
public void addStudent() throws Exception {
SqlSession sqlSession = factory.openSession(true); // 自动提交事务
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
System.out.println(studentMapper.getStudentById(1));
System.out.println("增长了" + studentMapper.addStudent(buildStudent()) + "个学生");
System.out.println(studentMapper.getStudentById(1));
sqlSession.close();
}
复制代码
执行结果:
咱们能够看到,在修改操做后执行的相同查询,查询了数据库,一级缓存失效。
开启两个SqlSession
,在sqlSession1
中查询数据,使一级缓存生效,在sqlSession2
中更新数据库,验证一级缓存只在数据库会话内部共享。
@Test
public void testLocalCacheScope() throws Exception {
SqlSession sqlSession1 = factory.openSession(true);
SqlSession sqlSession2 = factory.openSession(true);
StudentMapper studentMapper = sqlSession1.getMapper(StudentMapper.class);
StudentMapper studentMapper2 = sqlSession2.getMapper(StudentMapper.class);
System.out.println("studentMapper读取数据: " + studentMapper.getStudentById(1));
System.out.println("studentMapper读取数据: " + studentMapper.getStudentById(1));
System.out.println("studentMapper2更新了" + studentMapper2.updateStudentName("小岑",1) + "个学生的数据");
System.out.println("studentMapper读取数据: " + studentMapper.getStudentById(1));
System.out.println("studentMapper2读取数据: " + studentMapper2.getStudentById(1));
}
复制代码
sqlSession2
更新了id为1的学生的姓名,从凯伦改成了小岑,但session1以后的查询中,id为1的学生的名字仍是凯伦,出现了脏数据,也证实了以前的设想,一级缓存只在数据库会话内部共享。
那么,一级缓存的工做流程是怎样的呢?咱们从源码层面来学习一下。
一级缓存执行的时序图,以下图所示。
接下来将对MyBatis查询相关的核心类和一级缓存的源码进行走读。这对后面学习二级缓存也有帮助。
SqlSession: 对外提供了用户和数据库之间交互须要的全部方法,隐藏了底层的细节。默认实现类是DefaultSqlSession
。
Executor: SqlSession
向用户提供操做数据库的方法,但和数据库操做有关的职责都会委托给Executor。
以下图所示,Executor有若干个实现类,为Executor赋予了不一样的能力,你们能够根据类名,自行学习每一个类的基本做用。
在一级缓存的源码分析中,主要学习BaseExecutor
的内部实现。
BaseExecutor: BaseExecutor
是一个实现了Executor接口的抽象类,定义若干抽象方法,在执行的时候,把具体的操做委托给子类进行执行。
protected abstract int doUpdate(MappedStatement ms, Object parameter) throws SQLException;
protected abstract List<BatchResult> doFlushStatements(boolean isRollback) throws SQLException;
protected abstract <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException;
protected abstract <E> Cursor<E> doQueryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds, BoundSql boundSql) throws SQLException;
复制代码
在一级缓存的介绍中提到对Local Cache
的查询和写入是在Executor
内部完成的。在阅读BaseExecutor
的代码后发现Local Cache
是BaseExecutor
内部的一个成员变量,以下代码所示。
public abstract class BaseExecutor implements Executor {
protected ConcurrentLinkedQueue<DeferredLoad> deferredLoads;
protected PerpetualCache localCache;
复制代码
Cache: MyBatis中的Cache接口,提供了和缓存相关的最基本的操做,以下图所示:
有若干个实现类,使用装饰器模式互相组装,提供丰富的操控缓存的能力,部分实现类以下图所示:
BaseExecutor
成员变量之一的PerpetualCache
,是对Cache接口最基本的实现,其实现很是简单,内部持有HashMap,对一级缓存的操做实则是对HashMap的操做。以下代码所示:
public class PerpetualCache implements Cache {
private String id;
private Map<Object, Object> cache = new HashMap<Object, Object>();
复制代码
在阅读相关核心类代码后,从源代码层面对一级缓存工做中涉及到的相关代码,出于篇幅的考虑,对源码作适当删减,读者朋友能够结合本文,后续进行更详细的学习。
为执行和数据库的交互,首先须要初始化SqlSession
,经过DefaultSqlSessionFactory
开启SqlSession
:
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
............
final Executor executor = configuration.newExecutor(tx, execType);
return new DefaultSqlSession(configuration, executor, autoCommit);
}
复制代码
在初始化SqlSesion
时,会使用Configuration
类建立一个全新的Executor
,做为DefaultSqlSession
构造函数的参数,建立Executor代码以下所示:
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 = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
executor = new SimpleExecutor(this, transaction);
}
// 尤为能够注意这里,若是二级缓存开关开启的话,是使用CahingExecutor装饰BaseExecutor的子类
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
复制代码
SqlSession
建立完毕后,根据Statment的不一样类型,会进入SqlSession
的不一样方法中,若是是Select
语句的话,最后会执行到SqlSession
的selectList
,代码以下所示:
@Override
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
MappedStatement ms = configuration.getMappedStatement(statement);
return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
}
复制代码
SqlSession
把具体的查询职责委托给了Executor。若是只开启了一级缓存的话,首先会进入BaseExecutor
的query
方法。代码以下所示:
@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,进入该方法查看CacheKey是如何生成的,代码以下所示:
CacheKey cacheKey = new CacheKey();
cacheKey.update(ms.getId());
cacheKey.update(rowBounds.getOffset());
cacheKey.update(rowBounds.getLimit());
cacheKey.update(boundSql.getSql());
//后面是update了sql中带的参数
cacheKey.update(value);
复制代码
在上述的代码中,将MappedStatement
的Id、SQL的offset、SQL的limit、SQL自己以及SQL中的参数传入了CacheKey这个类,最终构成CacheKey。如下是这个类的内部结构:
private static final int DEFAULT_MULTIPLYER = 37;
private static final int DEFAULT_HASHCODE = 17;
private int multiplier;
private int hashcode;
private long checksum;
private int count;
private List<Object> updateList;
public CacheKey() {
this.hashcode = DEFAULT_HASHCODE;
this.multiplier = DEFAULT_MULTIPLYER;
this.count = 0;
this.updateList = new ArrayList<Object>();
}
复制代码
首先是成员变量和构造函数,有一个初始的hachcode
和乘数,同时维护了一个内部的updatelist
。在CacheKey
的update
方法中,会进行一个hashcode
和checksum
的计算,同时把传入的参数添加进updatelist
中。以下代码所示:
public void update(Object object) {
int baseHashCode = object == null ? 1 : ArrayUtil.hashCode(object);
count++;
checksum += baseHashCode;
baseHashCode *= count;
hashcode = multiplier * hashcode + baseHashCode;
updateList.add(object);
}
复制代码
同时重写了CacheKey
的equals
方法,代码以下所示:
@Override
public boolean equals(Object object) {
.............
for (int i = 0; i < updateList.size(); i++) {
Object thisObject = updateList.get(i);
Object thatObject = cacheKey.updateList.get(i);
if (!ArrayUtil.equals(thisObject, thatObject)) {
return false;
}
}
return true;
}
复制代码
除去hashcode、checksum和count的比较外,只要updatelist中的元素一一对应相等,那么就能够认为是CacheKey相等。只要两条SQL的下列五个值相同,便可以认为是相同的SQL。
Statement Id + Offset + Limmit + Sql + Params
BaseExecutor的query方法继续往下走,代码以下所示:
list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
if (list != null) {
// 这个主要是处理存储过程用的。
handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
} else {
list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
复制代码
若是查不到的话,就从数据库查,在queryFromDatabase
中,会对localcache
进行写入。
在query
方法执行的最后,会判断一级缓存级别是不是STATEMENT
级别,若是是的话,就清空缓存,这也就是STATEMENT
级别的一级缓存没法共享localCache
的缘由。代码以下所示:
if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
clearLocalCache();
}
复制代码
在源码分析的最后,咱们确认一下,若是是insert/delete/update
方法,缓存就会刷新的缘由。
SqlSession
的insert
方法和delete
方法,都会统一走update
的流程,代码以下所示:
@Override
public int insert(String statement, Object parameter) {
return update(statement, parameter);
}
@Override
public int delete(String statement) {
return update(statement, null);
}
复制代码
update
方法也是委托给了Executor
执行。BaseExecutor
的执行方法以下所示:
@Override
public int update(MappedStatement ms, Object parameter) throws SQLException {
ErrorContext.instance().resource(ms.getResource()).activity("executing an update").object(ms.getId());
if (closed) {
throw new ExecutorException("Executor was closed.");
}
clearLocalCache();
return doUpdate(ms, parameter);
}
复制代码
每次执行update
前都会清空localCache
。
至此,一级缓存的工做流程讲解以及源码分析完毕。
在上文中提到的一级缓存中,其最大的共享范围就是一个SqlSession内部,若是多个SqlSession之间须要共享缓存,则须要使用到二级缓存。开启二级缓存后,会使用CachingExecutor装饰Executor,进入一级缓存的查询流程前,先在CachingExecutor进行二级缓存的查询,具体的工做流程以下所示。
二级缓存开启后,同一个namespace下的全部操做语句,都影响着同一个Cache,即二级缓存被多个SqlSession共享,是一个全局的变量。
当开启缓存后,数据的查询执行的流程就是 二级缓存 -> 一级缓存 -> 数据库。
要正确的使用二级缓存,需完成以下配置的。
<setting name="cacheEnabled" value="true"/>
复制代码
cache标签用于声明这个namespace使用二级缓存,而且能够自定义配置。
<cache/>
复制代码
type
:cache使用的类型,默认是PerpetualCache
,这在一级缓存中提到过。eviction
: 定义回收的策略,常见的有FIFO,LRU。flushInterval
: 配置必定时间自动刷新缓存,单位是毫秒。size
: 最多缓存对象的个数。readOnly
: 是否只读,若配置可读写,则须要对应的实体类可以序列化。blocking
: 若缓存中找不到对应的key,是否会一直blocking,直到有对应的数据进入缓存。cache-ref
表明引用别的命名空间的Cache配置,两个命名空间的操做使用的是同一个Cache。
<cache-ref namespace="mapper.StudentMapper"/>
复制代码
接下来咱们经过实验,了解MyBatis二级缓存在使用上的一些特色。
在本实验中,id为1的学生名称初始化为点点。
测试二级缓存效果,不提交事务,sqlSession1
查询完数据后,sqlSession2
相同的查询是否会从缓存中获取数据。
@Test
public void testCacheWithoutCommitOrClose() throws Exception {
SqlSession sqlSession1 = factory.openSession(true);
SqlSession sqlSession2 = factory.openSession(true);
StudentMapper studentMapper = sqlSession1.getMapper(StudentMapper.class);
StudentMapper studentMapper2 = sqlSession2.getMapper(StudentMapper.class);
System.out.println("studentMapper读取数据: " + studentMapper.getStudentById(1));
System.out.println("studentMapper2读取数据: " + studentMapper2.getStudentById(1));
}
复制代码
执行结果:
咱们能够看到,当sqlsession
没有调用commit()
方法时,二级缓存并无起到做用。
测试二级缓存效果,当提交事务时,sqlSession1
查询完数据后,sqlSession2
相同的查询是否会从缓存中获取数据。
@Test
public void testCacheWithCommitOrClose() throws Exception {
SqlSession sqlSession1 = factory.openSession(true);
SqlSession sqlSession2 = factory.openSession(true);
StudentMapper studentMapper = sqlSession1.getMapper(StudentMapper.class);
StudentMapper studentMapper2 = sqlSession2.getMapper(StudentMapper.class);
System.out.println("studentMapper读取数据: " + studentMapper.getStudentById(1));
sqlSession1.commit();
System.out.println("studentMapper2读取数据: " + studentMapper2.getStudentById(1));
}
复制代码
从图上可知,sqlsession2
的查询,使用了缓存,缓存的命中率是0.5。
测试update
操做是否会刷新该namespace
下的二级缓存。
@Test
public void testCacheWithUpdate() throws Exception {
SqlSession sqlSession1 = factory.openSession(true);
SqlSession sqlSession2 = factory.openSession(true);
SqlSession sqlSession3 = factory.openSession(true);
StudentMapper studentMapper = sqlSession1.getMapper(StudentMapper.class);
StudentMapper studentMapper2 = sqlSession2.getMapper(StudentMapper.class);
StudentMapper studentMapper3 = sqlSession3.getMapper(StudentMapper.class);
System.out.println("studentMapper读取数据: " + studentMapper.getStudentById(1));
sqlSession1.commit();
System.out.println("studentMapper2读取数据: " + studentMapper2.getStudentById(1));
studentMapper3.updateStudentName("方方",1);
sqlSession3.commit();
System.out.println("studentMapper2读取数据: " + studentMapper2.getStudentById(1));
}
复制代码
咱们能够看到,在sqlSession3
更新数据库,并提交事务后,sqlsession2
的StudentMapper namespace
下的查询走了数据库,没有走Cache。
验证MyBatis的二级缓存不适应用于映射文件中存在多表查询的状况。
一般咱们会为每一个单表建立单独的映射文件,因为MyBatis的二级缓存是基于namespace
的,多表查询语句所在的namspace
没法感应到其余namespace
中的语句对多表查询中涉及的表进行的修改,引起脏数据问题。
@Test
public void testCacheWithDiffererntNamespace() throws Exception {
SqlSession sqlSession1 = factory.openSession(true);
SqlSession sqlSession2 = factory.openSession(true);
SqlSession sqlSession3 = factory.openSession(true);
StudentMapper studentMapper = sqlSession1.getMapper(StudentMapper.class);
StudentMapper studentMapper2 = sqlSession2.getMapper(StudentMapper.class);
ClassMapper classMapper = sqlSession3.getMapper(ClassMapper.class);
System.out.println("studentMapper读取数据: " + studentMapper.getStudentByIdWithClassInfo(1));
sqlSession1.close();
System.out.println("studentMapper2读取数据: " + studentMapper2.getStudentByIdWithClassInfo(1));
classMapper.updateClassName("特点一班",1);
sqlSession3.commit();
System.out.println("studentMapper2读取数据: " + studentMapper2.getStudentByIdWithClassInfo(1));
}
复制代码
执行结果:
在这个实验中,咱们引入了两张新的表,一张class,一张classroom。class中保存了班级的id和班级名,classroom中保存了班级id和学生id。咱们在StudentMapper
中增长了一个查询方法getStudentByIdWithClassInfo
,用于查询学生所在的班级,涉及到多表查询。在ClassMapper
中添加了updateClassName
,根据班级id更新班级名的操做。
当sqlsession1
的studentmapper
查询数据后,二级缓存生效。保存在StudentMapper的namespace下的cache中。当sqlSession3
的classMapper
的updateClassName
方法对class表进行更新时,updateClassName
不属于StudentMapper
的namespace
,因此StudentMapper
下的cache没有感应到变化,没有刷新缓存。当StudentMapper
中一样的查询再次发起时,从缓存中读取了脏数据。
为了解决实验4的问题呢,可使用Cache ref,让ClassMapper
引用StudenMapper
命名空间,这样两个映射文件对应的SQL操做都使用的是同一块缓存了。
执行结果:
不过这样作的后果是,缓存的粒度变粗了,多个Mapper namespace
下的全部操做都会对缓存使用形成影响。
MyBatis二级缓存的工做流程和前文提到的一级缓存相似,只是在一级缓存处理前,用CachingExecutor
装饰了BaseExecutor
的子类,在委托具体职责给delegate
以前,实现了二级缓存的查询和写入功能,具体类关系图以下图所示。
源码分析从CachingExecutor
的query
方法展开,源代码走读过程当中涉及到的知识点较多,不能一一详细讲解,读者朋友能够自行查询相关资料来学习。
CachingExecutor
的query
方法,首先会从MappedStatement
中得到在配置初始化时赋予的Cache。
Cache cache = ms.getCache();
复制代码
本质上是装饰器模式的使用,具体的装饰链是:
SynchronizedCache -> LoggingCache -> SerializedCache -> LruCache -> PerpetualCache。
如下是具体这些Cache实现类的介绍,他们的组合为Cache赋予了不一样的能力。
SynchronizedCache
:同步Cache,实现比较简单,直接使用synchronized修饰方法。LoggingCache
:日志功能,装饰类,用于记录缓存的命中率,若是开启了DEBUG模式,则会输出命中率日志。SerializedCache
:序列化功能,将值序列化后存到缓存中。该功能用于缓存返回一份实例的Copy,用于保存线程安全。LruCache
:采用了Lru算法的Cache实现,移除最近最少使用的Key/Value。PerpetualCache
: 做为为最基础的缓存类,底层实现比较简单,直接使用了HashMap。而后是判断是否须要刷新缓存,代码以下所示:
flushCacheIfRequired(ms);
复制代码
在默认的设置中SELECT
语句不会刷新缓存,insert/update/delte
会刷新缓存。进入该方法。代码以下所示:
private void flushCacheIfRequired(MappedStatement ms) {
Cache cache = ms.getCache();
if (cache != null && ms.isFlushCacheRequired()) {
tcm.clear(cache);
}
}
复制代码
MyBatis的CachingExecutor
持有了TransactionalCacheManager
,即上述代码中的tcm。
TransactionalCacheManager
中持有了一个Map,代码以下所示:
private Map<Cache, TransactionalCache> transactionalCaches = new HashMap<Cache, TransactionalCache>();
复制代码
这个Map保存了Cache和用TransactionalCache
包装后的Cache的映射关系。
TransactionalCache
实现了Cache接口,CachingExecutor
会默认使用他包装初始生成的Cache,做用是若是事务提交,对缓存的操做才会生效,若是事务回滚或者不提交事务,则不对缓存产生影响。
在TransactionalCache
的clear,有如下两句。清空了须要在提交时加入缓存的列表,同时设定提交时清空缓存,代码以下所示:
@Override
public void clear() {
clearOnCommit = true;
entriesToAddOnCommit.clear();
}
复制代码
CachingExecutor
继续往下走,ensureNoOutParams
主要是用来处理存储过程的,暂时不用考虑。
if (ms.isUseCache() && resultHandler == null) {
ensureNoOutParams(ms, parameterObject, boundSql);
复制代码
以后会尝试从tcm中获取缓存的列表。
List<E> list = (List<E>) tcm.getObject(cache, key);
复制代码
在getObject
方法中,会把获取值的职责一路传递,最终到PerpetualCache
。若是没有查到,会把key加入Miss集合,这个主要是为了统计命中率。
Object object = delegate.getObject(key);
if (object == null) {
entriesMissedInCache.add(key);
}
复制代码
CachingExecutor
继续往下走,若是查询到数据,则调用tcm.putObject
方法,往缓存中放入值。
if (list == null) {
list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
tcm.putObject(cache, key, list); // issue #578 and #116
}
复制代码
tcm的put
方法也不是直接操做缓存,只是在把此次的数据和key放入待提交的Map中。
@Override
public void putObject(Object key, Object object) {
entriesToAddOnCommit.put(key, object);
}
复制代码
从以上的代码分析中,咱们能够明白,若是不调用commit
方法的话,因为TranscationalCache
的做用,并不会对二级缓存形成直接的影响。所以咱们看看Sqlsession
的commit
方法中作了什么。代码以下所示:
@Override
public void commit(boolean force) {
try {
executor.commit(isCommitOrRollbackRequired(force));
复制代码
由于咱们使用了CachingExecutor,首先会进入CachingExecutor实现的commit方法。
@Override
public void commit(boolean required) throws SQLException {
delegate.commit(required);
tcm.commit();
}
复制代码
会把具体commit的职责委托给包装的Executor
。主要是看下tcm.commit()
,tcm最终又会调用到TrancationalCache
。
public void commit() {
if (clearOnCommit) {
delegate.clear();
}
flushPendingEntries();
reset();
}
复制代码
看到这里的clearOnCommit
就想起刚才TrancationalCache
的clear
方法设置的标志位,真正的清理Cache是放到这里来进行的。具体清理的职责委托给了包装的Cache类。以后进入flushPendingEntries
方法。代码以下所示:
private void flushPendingEntries() {
for (Map.Entry<Object, Object> entry : entriesToAddOnCommit.entrySet()) {
delegate.putObject(entry.getKey(), entry.getValue());
}
................
}
复制代码
在flushPending
Entries中,将待提交的Map进行循环处理,委托给包装的Cache类,进行putObject
的操做。
后续的查询操做会重复执行这套流程。若是是insert|update|delete
的话,会统一进入CachingExecutor
的update
方法,其中调用了这个函数,代码以下所示:
private void flushCacheIfRequired(MappedStatement ms)
复制代码
在二级缓存执行流程后就会进入一级缓存的执行流程,所以再也不赘述。
SqlSession
之间缓存数据的共享,同时粒度更加的细,可以到namespace
级别,经过Cache接口实现类不一样的组合,对Cache的可控性也更强。本文对介绍了MyBatis一二级缓存的基本概念,并从应用及源码的角度对MyBatis的缓存机制进行了分析。最后对MyBatis缓存机制作了必定的总结,我的建议MyBatis缓存特性在生产环境中进行关闭,单纯做为一个ORM框架使用可能更为合适。