MyBatis支持聲明式數據緩存(declarative data caching)。當一條SQL語句被標記爲「可緩存」後,首次執行它時從數據庫獲取的全部數據會被存儲在一段高速緩存中,從此執行這條語句時就會從高速緩存中讀取結果,而不是再次命中數據庫。MyBatis提供了默認下基於Java HashMap的緩存實現,以及用於與OSCache、Ehcache、Hazelcast和Memcached鏈接的默認鏈接器。MyBatis還提供API供其餘緩存實現使用。html
重點的那句話就是:MyBatis執行SQL語句以後,這條語句就是被緩存,之後再執行這條語句的時候,會直接從緩存中拿結果,而不是再次執行SQLjava
這也就是你們常說的MyBatis一級緩存,一級緩存的做用域scope是SqlSession。node
MyBatis同時還提供了一種全局做用域global scope的緩存,這也叫作二級緩存,也稱做全局緩存。sql
同個session進行兩次相同查詢:數據庫
1
2
3
4
5
6
7
8
9
10
11
12
|
@Test
public
void
test() {
SqlSession sqlSession = sqlSessionFactory.openSession();
try
{
User user = (User)sqlSession.selectOne(
"org.format.mybatis.cache.UserMapper.getById"
,
1
);
log.debug(user);
User user2 = (User)sqlSession.selectOne(
"org.format.mybatis.cache.UserMapper.getById"
,
1
);
log.debug(user2);
}
finally
{
sqlSession.close();
}
}
|
MyBatis只進行1次數據庫查詢:apache
1
2
3
4
5
|
==> Preparing: select * from USERS WHERE ID = ?
==> Parameters:
1
(Integer)
<== Total:
1
User{id=
1
, name=
'format'
, age=
23
, birthday=Sun Oct
12
23
:
20
:
13
CST
2014
}
User{id=
1
, name=
'format'
, age=
23
, birthday=Sun Oct
12
23
:
20
:
13
CST
2014
}
|
同個session進行兩次不一樣的查詢:設計模式
1
2
3
4
5
6
7
8
9
10
11
12
|
@Test
public
void
test() {
SqlSession sqlSession = sqlSessionFactory.openSession();
try
{
User user = (User)sqlSession.selectOne(
"org.format.mybatis.cache.UserMapper.getById"
,
1
);
log.debug(user);
User user2 = (User)sqlSession.selectOne(
"org.format.mybatis.cache.UserMapper.getById"
,
2
);
log.debug(user2);
}
finally
{
sqlSession.close();
}
}
|
MyBatis進行兩次數據庫查詢:緩存
1
2
3
4
5
6
7
8
|
==> Preparing: select * from USERS WHERE ID = ?
==> Parameters:
1
(Integer)
<== Total:
1
User{id=
1
, name=
'format'
, age=
23
, birthday=Sun Oct
12
23
:
20
:
13
CST
2014
}
==> Preparing: select * from USERS WHERE ID = ?
==> Parameters:
2
(Integer)
<== Total:
1
User{id=
2
, name=
'FFF'
, age=
50
, birthday=Sat Dec
06
17
:
12
:
01
CST
2014
}
|
不一樣session,進行相同查詢:session
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@Test
public
void
test() {
SqlSession sqlSession = sqlSessionFactory.openSession();
SqlSession sqlSession2 = sqlSessionFactory.openSession();
try
{
User user = (User)sqlSession.selectOne(
"org.format.mybatis.cache.UserMapper.getById"
,
1
);
log.debug(user);
User user2 = (User)sqlSession2.selectOne(
"org.format.mybatis.cache.UserMapper.getById"
,
1
);
log.debug(user2);
}
finally
{
sqlSession.close();
sqlSession2.close();
}
}
|
MyBatis進行了兩次數據庫查詢:mybatis
1
2
3
4
5
6
7
8
|
==> Preparing: select * from USERS WHERE ID = ?
==> Parameters:
1
(Integer)
<== Total:
1
User{id=
1
, name=
'format'
, age=
23
, birthday=Sun Oct
12
23
:
20
:
13
CST
2014
}
==> Preparing: select * from USERS WHERE ID = ?
==> Parameters:
1
(Integer)
<== Total:
1
User{id=
1
, name=
'format'
, age=
23
, birthday=Sun Oct
12
23
:
20
:
13
CST
2014
}
|
同個session,查詢以後更新數據,再次查詢相同的語句:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@Test
public
void
test() {
SqlSession sqlSession = sqlSessionFactory.openSession();
try
{
User user = (User)sqlSession.selectOne(
"org.format.mybatis.cache.UserMapper.getById"
,
1
);
log.debug(user);
user.setAge(
100
);
sqlSession.update(
"org.format.mybatis.cache.UserMapper.update"
, user);
User user2 = (User)sqlSession.selectOne(
"org.format.mybatis.cache.UserMapper.getById"
,
1
);
log.debug(user2);
sqlSession.commit();
}
finally
{
sqlSession.close();
}
}
|
更新操做以後緩存會被清除:
1
2
3
4
5
6
7
8
9
10
11
|
==> Preparing: select * from USERS WHERE ID = ?
==> Parameters:
1
(Integer)
<== Total:
1
User{id=
1
, name=
'format'
, age=
23
, birthday=Sun Oct
12
23
:
20
:
13
CST
2014
}
==> Preparing: update USERS SET NAME = ? , AGE = ? , BIRTHDAY = ? where ID = ?
==> Parameters: format(String),
23
(Integer),
2014
-
10
-
12
23
:
20
:
13.0
(Timestamp),
1
(Integer)
<== Updates:
1
==> Preparing: select * from USERS WHERE ID = ?
==> Parameters:
1
(Integer)
<== Total:
1
User{id=
1
, name=
'format'
, age=
23
, birthday=Sun Oct
12
23
:
20
:
13
CST
2014
}
|
很明顯,結果驗證了一級緩存的概念,在同個SqlSession中,查詢語句相同的sql會被緩存,可是一旦執行新增或更新或刪除操做,緩存就會被清除
在分析MyBatis的一級緩存以前,咱們先簡單看下MyBatis中幾個重要的類和接口:
org.apache.ibatis.session.Configuration類:MyBatis全局配置信息類
org.apache.ibatis.session.SqlSessionFactory接口:操做SqlSession的工廠接口,具體的實現類是DefaultSqlSessionFactory
org.apache.ibatis.session.SqlSession接口:執行sql,管理事務的接口,具體的實現類是DefaultSqlSession
org.apache.ibatis.executor.Executor接口:sql執行器,SqlSession執行sql最終是經過該接口實現的,經常使用的實現類有SimpleExecutor和CachingExecutor,這些實現類都使用了裝飾者設計模式
一級緩存的做用域是SqlSession,那麼咱們就先看一下SqlSession的select過程:
這是DefaultSqlSession(SqlSession接口實現類,MyBatis默認使用這個類)的selectList源碼(咱們例子上使用的是selectOne方法,調用selectOne方法最終會執行selectList方法):
1
2
3
4
5
6
7
8
9
10
11
|
public
<E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
try
{
MappedStatement ms = configuration.getMappedStatement(statement);
List<E> result = executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
return
result;
}
catch
(Exception e) {
throw
ExceptionFactory.wrapException(
"Error querying database. Cause: "
+ e, e);
}
finally
{
ErrorContext.instance().reset();
}
}
|
咱們看到SqlSession最終會調用Executor接口的方法。
接下來咱們看下DefaultSqlSession中的executor接口屬性具體是哪一個實現類。
DefaultSqlSession的構造過程(DefaultSqlSessionFactory內部):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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, autoCommit);
return
new
DefaultSqlSession(configuration, executor);
}
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();
}
}
|
咱們看到DefaultSqlSessionFactory構造DefaultSqlSession的時候,Executor接口的實現類是由Configuration構造的:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public
Executor newExecutor(Transaction transaction, ExecutorType executorType,
boolean
autoCommit) {
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);
}
if
(cacheEnabled) {
executor =
new
CachingExecutor(executor, autoCommit);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return
executor;
}
|
Executor根據ExecutorType的不一樣而建立,最經常使用的是SimpleExecutor,本文的例子也是建立這個實現類。 最後咱們發現若是cacheEnabled這個屬性爲true的話,那麼executor會被包一層裝飾器,這個裝飾器是CachingExecutor。其中cacheEnabled這個屬性是mybatis總配置文件中settings節點中cacheEnabled子節點的值,默認就是true,也就是說咱們在mybatis總配置文件中不配cacheEnabled的話,它也是默認爲打開的。
如今,問題就剩下一個了,CachingExecutor執行sql的時候到底作了什麼?
帶着這個問題,咱們繼續走下去(CachingExecutor的query方法):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public
<E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
throws
SQLException {
Cache cache = ms.getCache();
if
(cache !=
null
) {
flushCacheIfRequired(ms);
if
(ms.isUseCache() && resultHandler ==
null
) {
ensureNoOutParams(ms, parameterObject, boundSql);
if
(!dirty) {
cache.getReadWriteLock().readLock().lock();
try
{
@SuppressWarnings
(
"unchecked"
)
List<E> cachedList = (List<E>) cache.getObject(key);
if
(cachedList !=
null
)
return
cachedList;
}
finally
{
cache.getReadWriteLock().readLock().unlock();
}
}
List<E> list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
tcm.putObject(cache, key, list);
// issue #578. Query must be not synchronized to prevent deadlocks
return
list;
}
}
return
delegate.<E>query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
|
其中Cache cache = ms.getCache();這句代碼中,這個cache實際上就是個二級緩存,因爲咱們沒有開啓二級緩存(二級緩存的內容下面會分析),所以這裏執行了最後一句話。這裏的delegate也就是SimpleExecutor,SimpleExecutor沒有Override父類的query方法,所以最終執行了SimpleExecutor的父類BaseExecutor的query方法。
因此一級緩存最重要的代碼就是BaseExecutor的query方法!
BaseExecutor的屬性localCache是個PerpetualCache類型的實例,PerpetualCache類是實現了MyBatis的Cache緩存接口的實現類之一,內部有個Map類型的屬性用來存儲緩存數據。 這個localCache的類型在BaseExecutor內部是寫死的。 這個localCache就是一級緩存!
接下來咱們看下爲什麼執行新增或更新或刪除操做,一級緩存就會被清除這個問題。
首先MyBatis處理新增或刪除的時候,最終都是調用update方法,也就是說新增或者刪除操做在MyBatis眼裏都是一個更新操做。
咱們看下DefaultSqlSession的update方法:
1
2
3
4
5
6
7
8
9
10
11
|
public
int
update(String statement, Object parameter) {
try
{
dirty =
true
;
MappedStatement ms = configuration.getMappedStatement(statement);
return
executor.update(ms, wrapCollection(parameter));
}
catch
(Exception e) {
throw
ExceptionFactory.wrapException(
"Error updating database. Cause: "
+ e, e);
}
finally
{
ErrorContext.instance().reset();
}
}
|
很明顯,這裏調用了CachingExecutor的update方法:
1
2
3
4
|
public
int
update(MappedStatement ms, Object parameterObject)
throws
SQLException {
flushCacheIfRequired(ms);
return
delegate.update(ms, parameterObject);
}
|
這裏的flushCacheIfRequired方法清除的是二級緩存,咱們以後會分析。 CachingExecutor委託給了(以前已經分析過)SimpleExecutor的update方法,SimpleExecutor沒有Override父類BaseExecutor的update方法,所以咱們看BaseExecutor的update方法:
1
2
3
4
5
6
|
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);
}
|
咱們看到了關鍵的一句代碼: clearLocalCache(); 進去看看:
1
2
3
4
5
6
|
public
void
clearLocalCache() {
if
(!closed) {
localCache.clear();
localOutputParameterCache.clear();
}
}
|
沒錯,就是這條,sqlsession沒有關閉的話,進行新增、刪除、修改操做的話就是清除一級緩存,也就是SqlSession的緩存。
二級緩存的做用域是全局,換句話說,二級緩存已經脫離SqlSession的控制了。
在測試二級緩存以前,我先把結論說一下:
二級緩存的做用域是全局的,二級緩存在SqlSession關閉或提交以後纔會生效。
在分析MyBatis的二級緩存以前,咱們先簡單看下MyBatis中一個關於二級緩存的類(其餘相關的類和接口以前已經分析過):
org.apache.ibatis.mapping.MappedStatement:
MappedStatement類在Mybatis框架中用於表示XML文件中一個sql語句節點,即一個<select />、<update />或者<insert />標籤。Mybatis框架在初始化階段會對XML配置文件進行讀取,將其中的sql語句節點對象化爲一個個MappedStatement對象。
二級緩存跟一級緩存不一樣,一級緩存不須要配置任何東西,且默認打開。 二級緩存就須要配置一些東西。
本文就說下最簡單的配置,在mapper文件上加上這句配置便可:
1
|
<
cache
/>
|
其實二級緩存跟3個配置有關:
不一樣SqlSession,查詢相同語句,第一次查詢以後commit SqlSession:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
@Test
public
void
testCache2() {
SqlSession sqlSession = sqlSessionFactory.openSession();
SqlSession sqlSession2 = sqlSessionFactory.openSession();
try
{
String sql =
"org.format.mybatis.cache.UserMapper.getById"
;
User user = (User)sqlSession.selectOne(sql,
1
);
log.debug(user);
// 注意,這裏必定要提交。 不提交仍是會查詢兩次數據庫
sqlSession.commit();
User user2 = (User)sqlSession2.selectOne(sql,
1
);
log.debug(user2);
}
finally
{
sqlSession.close();
sqlSession2.close();
}
}
|
MyBatis僅進行了一次數據庫查詢:
1
2
3
4
5
|
==> Preparing: select * from USERS WHERE ID = ?
==> Parameters:
1
(Integer)
<== Total:
1
User{id=
1
, name=
'format'
, age=
23
, birthday=Sun Oct
12
23
:
20
:
13
CST
2014
}
User{id=
1
, name=
'format'
, age=
23
, birthday=Sun Oct
12
23
:
20
:
13
CST
2014
}
|
不一樣SqlSession,查詢相同語句,第一次查詢以後close SqlSession:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@Test
public
void
testCache2() {
SqlSession sqlSession = sqlSessionFactory.openSession();
SqlSession sqlSession2 = sqlSessionFactory.openSession();
try
{
String sql =
"org.format.mybatis.cache.UserMapper.getById"
;
User user = (User)sqlSession.selectOne(sql,
1
);
log.debug(user);
sqlSession.close();
User user2 = (User)sqlSession2.selectOne(sql,
1
);
log.debug(user2);
}
finally
{
sqlSession2.close();
}
}
|
MyBatis僅進行了一次數據庫查詢:
1
2
3
4
5
|
==> Preparing: select * from USERS WHERE ID = ?
==> Parameters:
1
(Integer)
<== Total:
1
User{id=
1
, name=
'format'
, age=
23
, birthday=Sun Oct
12
23
:
20
:
13
CST
2014
}
User{id=
1
, name=
'format'
, age=
23
, birthday=Sun Oct
12
23
:
20
:
13
CST
2014
}
|
不一樣SqlSesson,查詢相同語句。 第一次查詢以後SqlSession不提交:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@Test
public
void
testCache2() {
SqlSession sqlSession = sqlSessionFactory.openSession();
SqlSession sqlSession2 = sqlSessionFactory.openSession();
try
{
String sql =
"org.format.mybatis.cache.UserMapper.getById"
;
User user = (User)sqlSession.selectOne(sql,
1
);
log.debug(user);
User user2 = (User)sqlSession2.selectOne(sql,
1
);
log.debug(user2);
}
finally
{
sqlSession.close();
sqlSession2.close();
}
}
|
MyBatis執行了兩次數據庫查詢:
1
2
3
4
5
6
7
8
|
==> Preparing: select * from USERS WHERE ID = ?
==> Parameters:
1
(Integer)
<== Total:
1
User{id=
1
, name=
'format'
, age=
23
, birthday=Sun Oct
12
23
:
20
:
13
CST
2014
}
==> Preparing: select * from USERS WHERE ID = ?
==> Parameters:
1
(Integer)
<== Total:
1
User{id=
1
, name=
'format'
, age=
23
, birthday=Sun Oct
12
23
:
20
:
13
CST
2014
}
|
咱們從在mapper文件中加入的<cache/>中開始分析源碼,關於MyBatis的SQL解析請參考另一篇博客Mybatis解析動態sql原理分析。接下來咱們看下這個cache的解析:
XMLMappedBuilder(解析每一個mapper配置文件的解析類,每個mapper配置都會實例化一個XMLMapperBuilder類)的解析方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
private
void
configurationElement(XNode context) {
try
{
String namespace = context.getStringAttribute(
"namespace"
);
if
(namespace.equals(
""
)) {
throw
new
BuilderException(
"Mapper's namespace cannot be empty"
);
}
builderAssistant.setCurrentNamespace(namespace);
cacheRefElement(context.evalNode(
"cache-ref"
));
cacheElement(context.evalNode(
"cache"
));
parameterMapElement(context.evalNodes(
"/mapper/parameterMap"
));
resultMapElements(context.evalNodes(
"/mapper/resultMap"
));
sqlElement(context.evalNodes(
"/mapper/sql"
));
buildStatementFromContext(context.evalNodes(
"select|insert|update|delete"
));
}
catch
(Exception e) {
throw
new
BuilderException(
"Error parsing Mapper XML. Cause: "
+ e, e);
}
}
|
咱們看到了解析cache的那段代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
private
void
cacheElement(XNode context)
throws
Exception {
if
(context !=
null
) {
String type = context.getStringAttribute(
"type"
,
"PERPETUAL"
);
Class<?
extends
Cache> typeClass = typeAliasRegistry.resolveAlias(type);
String eviction = context.getStringAttribute(
"eviction"
,
"LRU"
);
Class<?
extends
Cache> evictionClass = typeAliasRegistry.resolveAlias(eviction);
Long flushInterval = context.getLongAttribute(
"flushInterval"
);
Integer size = context.getIntAttribute(
"size"
);
boolean
readWrite = !context.getBooleanAttribute(
"readOnly"
,
false
);
Properties props = context.getChildrenAsProperties();
builderAssistant.useNewCache(typeClass, evictionClass, flushInterval, size, readWrite, props);
}
}
|
解析完cache標籤以後會使用builderAssistant的userNewCache方法,這裏的builderAssistant是一個MapperBuilderAssistant類型的幫助類,每一個XMLMappedBuilder構造的時候都會實例化這個屬性,MapperBuilderAssistant類內部有個Cache類型的currentCache屬性,這個屬性也就是mapper配置文件中cache節點所表明的值:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public
Cache useNewCache(Class<?
extends
Cache> typeClass,
Class<?
extends
Cache> evictionClass,
Long flushInterval,
Integer size,
boolean
readWrite,
Properties props) {
typeClass = valueOrDefault(typeClass, PerpetualCache.
class
);
evictionClass = valueOrDefault(evictionClass, LruCache.
class
);
Cache cache =
new
CacheBuilder(currentNamespace)
.implementation(typeClass)
.addDecorator(evictionClass)
.clearInterval(flushInterval)
.size(size)
.readWrite(readWrite)
.properties(props)
.build();
configuration.addCache(cache);
currentCache = cache;
return
cache;
}
|
ok,如今mapper配置文件中的cache節點被解析到了XMLMapperBuilder實例中的builderAssistant屬性中的currentCache值裏。
接下來XMLMapperBuilder會解析select節點,解析select節點的時候使用XMLStatementBuilder進行解析(也包括其餘insert,update,delete節點):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
public
void
parseStatementNode() {
String id = context.getStringAttribute(
"id"
);
String databaseId = context.getStringAttribute(
"databaseId"
);
if
(!databaseIdMatchesCurrent(id, databaseId,
this
.requiredDatabaseId))
return
;
Integer fetchSize = context.getIntAttribute(
"fetchSize"
);
Integer timeout = context.getIntAttribute(
"timeout"
);
String parameterMap = context.getStringAttribute(
"parameterMap"
);
String parameterType = context.getStringAttribute(
"parameterType"
);
Class<?> parameterTypeClass = resolveClass(parameterType);
String resultMap = context.getStringAttribute(
"resultMap"
);
String resultType = context.getStringAttribute(
"resultType"
);
String lang = context.getStringAttribute(
"lang"
);
LanguageDriver langDriver = getLanguageDriver(lang);
Class<?> resultTypeClass = resolveClass(resultType);
String resultSetType = context.getStringAttribute(
"resultSetType"
);
StatementType statementType = StatementType.valueOf(context.getStringAttribute(
"statementType"
, StatementType.PREPARED.toString()));
ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType);
String nodeName = context.getNode().getNodeName();
SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));
boolean
isSelect = sqlCommandType == SqlCommandType.SELECT;
boolean
flushCache = context.getBooleanAttribute(
"flushCache"
, !isSelect);
boolean
useCache = context.getBooleanAttribute(
"useCache"
, isSelect);
boolean
resultOrdered = context.getBooleanAttribute(
"resultOrdered"
,
false
);
// Include Fragments before parsing
XMLIncludeTransformer includeParser =
new
XMLIncludeTransformer(configuration, builderAssistant);
includeParser.applyIncludes(context.getNode());
// Parse selectKey after includes and remove them.
processSelectKeyNodes(id, parameterTypeClass, langDriver);
// Parse the SQL (pre: <selectKey> and <include> were parsed and removed)
SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
String resultSets = context.getStringAttribute(
"resultSets"
);
String keyProperty = context.getStringAttribute(
"keyProperty"
);
String keyColumn = context.getStringAttribute(
"keyColumn"
);
KeyGenerator keyGenerator;
String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX;
keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId,
true
);
if
(configuration.hasKeyGenerator(keyStatementId)) {
keyGenerator = configuration.getKeyGenerator(keyStatementId);
}
else
{
keyGenerator = context.getBooleanAttribute(
"useGeneratedKeys"
,
configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))
?
new
Jdbc3KeyGenerator() :
new
NoKeyGenerator();
}
builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
resultSetTypeEnum, flushCache, useCache, resultOrdered,
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
}
|
這段代碼前面都是解析一些標籤的屬性,咱們看到了最後一行使用builderAssistant添加MappedStatement,其中builderAssistant屬性是構造XMLStatementBuilder的時候經過XMLMappedBuilder傳入的,咱們繼續看builderAssistant的addMappedStatement方法:
進入setStatementCache:
1
2
3
4
5
6
7
8
9
10
11
12
|
private
void
setStatementCache(
boolean
isSelect,
boolean
flushCache,
boolean
useCache,
Cache cache,
MappedStatement.Builder statementBuilder) {
flushCache = valueOrDefault(flushCache, !isSelect);
useCache = valueOrDefault(useCache, isSelect);
statementBuilder.flushCacheRequired(flushCache);
statementBuilder.useCache(useCache);
statementBuilder.cache(cache);
}
|
最終mapper配置文件中的<cache/>被設置到了XMLMapperBuilder的builderAssistant屬性中,XMLMapperBuilder中使用XMLStatementBuilder遍歷CRUD節點,遍歷CRUD節點的時候將這個cache節點設置到這些CRUD節點中,這個cache就是所謂的二級緩存!
接下來咱們回過頭來看查詢的源碼,CachingExecutor的query方法:
進入TransactionalCacheManager的putObject方法:
1
2
3
4
5
6
7
8
9
10
11
12
|
public
void
putObject(Cache cache, CacheKey key, Object value) {
getTransactionalCache(cache).putObject(key, value);
}
private
TransactionalCache getTransactionalCache(Cache cache) {
TransactionalCache txCache = transactionalCaches.get(cache);
if
(txCache ==
null
) {
txCache =
new
TransactionalCache(cache);
transactionalCaches.put(cache, txCache);
}
return
txCache;
}
|
TransactionalCache的putObject方法:
1
2
3
4
|
public
void
putObject(Object key, Object object) {
entriesToRemoveOnCommit.remove(key);
entriesToAddOnCommit.put(key,
new
AddEntry(delegate, key, object));
}
|
咱們看到,數據被加入到了entriesToAddOnCommit中,這個entriesToAddOnCommit是什麼東西呢,它是TransactionalCache的一個Map屬性:
1
|
private
Map<Object, AddEntry> entriesToAddOnCommit;
|
AddEntry是TransactionalCache內部的一個類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
private
static
class
AddEntry {
private
Cache cache;
private
Object key;
private
Object value;
public
AddEntry(Cache cache, Object key, Object value) {
this
.cache = cache;
this
.key = key;
this
.value = value;
}
public
void
commit() {
cache.putObject(key, value);
}
}
|
好了,如今咱們發現使用二級緩存以後:查詢數據的話,先從二級緩存中拿數據,若是沒有的話,去一級緩存中拿,一級緩存也沒有的話再查詢數據庫。有了數據以後在丟到TransactionalCache這個對象的entriesToAddOnCommit屬性中。
接下來咱們來驗證爲何SqlSession commit或close以後,二級緩存纔會生效這個問題。
DefaultSqlSession的commit方法:
1
2
3
4
5
6
7
8
9
10
|
public
void
commit(
boolean
force) {
try
{
executor.commit(isCommitOrRollbackRequired(force));
dirty =
false
;
}
catch
(Exception e) {
throw
ExceptionFactory.wrapException(
"Error committing transaction. Cause: "
+ e, e);
}
finally
{
ErrorContext.instance().reset();
}
}
|
CachingExecutor的commit方法:
1
2
3
4
5
|
public
void
commit(
boolean
required)
throws
SQLException {
delegate.commit(required);
tcm.commit();
dirty =
false
;
}
|
tcm.commit即 TransactionalCacheManager的commit方法:
1
2
3
4
5
|
public
void
commit() {
for
(TransactionalCache txCache : transactionalCaches.values()) {
txCache.commit();
}
}
|
TransactionalCache的commit方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public
void
commit() {
delegate.getReadWriteLock().writeLock().lock();
try
{
if
(clearOnCommit) {
delegate.clear();
}
else
{
for
(RemoveEntry entry : entriesToRemoveOnCommit.values()) {
entry.commit();
}
}
for
(AddEntry entry : entriesToAddOnCommit.values()) {
entry.commit();
}
reset();
}
finally
{
delegate.getReadWriteLock().writeLock().unlock();
}
}
|
發現調用了AddEntry的commit方法:
1
2
3
|
public
void
commit() {
cache.putObject(key, value);
}
|
發現了! AddEntry的commit方法會把數據丟到cache中,也就是丟到二級緩存中!
關於爲什麼調用close方法後,二級緩存纔會生效,由於close方法內部會調用commit方法。本文就不具體說了。 讀者有興趣的話看一看源碼就知道爲何了。
org.apache.ibatis.cache.Cache是MyBatis的緩存接口,想要實現自定義的緩存須要實現這個接口。
MyBatis中關於Cache接口的實現類也使用了裝飾者設計模式。
咱們看下它的一些實現類
簡單說明:
LRU – 最近最少使用的:移除最長時間不被使用的對象。
FIFO – 先進先出:按對象進入緩存的順序來移除它們。
SOFT – 軟引用:移除基於垃圾回收器狀態和軟引用規則的對象。
WEAK – 弱引用:更積極地移除基於垃圾收集器狀態和弱引用規則的對象。
1
2
3
4
5
|
<
cache
eviction
=
"FIFO"
flushInterval
=
"60000"
size
=
"512"
readOnly
=
"true"
/>
|
能夠經過cache節點的eviction屬性設置,也能夠設置其餘的屬性。
mapper配置文件中還能夠加入cache-ref節點,它有個屬性namespace。
若是每一個mapper文件都是用cache-ref,且namespace都同樣,那麼就表明着真正意義上的全局緩存。
若是隻用了cache節點,那僅表明這個這個mapper內部的查詢被緩存了,其餘mapper文件的不起做用,這並非所謂的全局緩存。
整體來講,MyBatis的源碼看起來仍是比較輕鬆的,本文從實踐和源碼方面深刻分析了MyBatis的緩存原理,但願對讀者有幫助
歡迎學Java和大數據的朋友們加入java架構交流: 855835163
加羣連接:jq.qq.com/?_wv=1027&a…羣內提供免費的架構資料還有:Java工程化、高性能及分佈式、高性能、深刻淺出。高架構。性能調優、Spring,MyBatis,Netty源碼分析和大數據等多個知識點高級進階乾貨的免費直播講解 能夠進來一塊兒學習交流哦