一、概要
mybatis的緩存分為一級緩存和二級緩存。一級緩存是本地緩存,SqlSession級別的。二級緩存是全局緩存。
二、緩存體驗
- 一級緩存體驗
@Test
public void testFirstLevelCache(){
SqlSession sqlSession = null;
try{
sqlSession = getSession();
CacheMapper mapper = sqlSession.getMapper(CacheMapper.class);
Employee e1 = mapper.testFirstLevelCache(1);
System.out.println("第一次查詢完畢");
Employee e2 = mapper.testFirstLevelCache(1);
System.out.println("第二次查詢完畢");
boolean b = (e1 == e2);
System.out.println("e1與e2是否相等:" + b);
}catch (Exception e){
e.printStackTrace();
}finally {
sqlSession.close();
}
}
此例中,使用同一個sqlSession進行查詢,然后判斷兩個對象是否相等。結果如下:
DEBUG [main] - ==> Preparing: SELECT * FROM tbl_employee where id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
第一次查詢完畢
第二次查詢完畢
e1與e2是否相等:true
從控制臺打印結果可以看出,同一會話中的兩次查詢,只發(fā)送了一條sql語句,并且兩次查詢出的對象是相等的。如此可以體驗到mybatis提供的一級緩存。
- 二級緩存體驗
二級緩存是mybatis的全局緩存,需要進行一些配置項的設置才可以生效。
在全局配置文件中,有如下配置項,用來設置全局緩存的開啟或者關閉。
<setting name="cacheEnabled" value="true"></setting>
然后,在需要使用二級緩存的mapper.xml中,配置如下選項,標識此mapper使用二級緩存,并設置與二級緩存相關的各種參數(shù)。
<mapper namespace="com.hly.dao.CacheMapper">
<cache></cache>
<select id="testFirstLevelCache" resultType="com.hly.entity.Employee">
SELECT * FROM tbl_employee where id=#{id}
</select>
</mapper>
在完成以上配置之后,體驗二級緩存之前,還有一個地方需要注意。二級緩存中的內容,是在sqlSession關閉后,將本sqlSession的緩存結果放入二級緩存。
@Test
public void testSecondLevelCache(){
SqlSession sqlSession = null;
SqlSession sqlSession2 = null;
try{
sqlSession = getSession();
sqlSession2 = getSession();
CacheMapper mapper = sqlSession.getMapper(CacheMapper.class);
Employee e1 = mapper.testFirstLevelCache(1); // 方法名懶得改了
System.out.println("查詢1完成");
sqlSession.close();
CacheMapper mapper2 = sqlSession2.getMapper(CacheMapper.class);
Employee e2 = mapper2.testFirstLevelCache(1);
System.out.println("查詢2完成");
boolean b = (e1 == e2);
System.out.println("e1與e2是否相等:" + b);
} catch(Exception e){
e.printStackTrace();
} finally {
sqlSession2.close();
}
}
代碼寫好后,滿懷欣喜的等待執(zhí)行結果,卻未曾料想得到以下驚喜:
DEBUG [main] - Cache Hit Ratio [com.hly.dao.CacheMapper]: 0.0
DEBUG [main] - ==> Preparing: SELECT * FROM tbl_employee where id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
查詢1完成
org.apache.ibatis.cache.CacheException: Error serializing object. Cause: java.io.NotSerializableException: com.hly.entity.Employee
at org.apache.ibatis.cache.decorators.SerializedCache.serialize(SerializedCache.java:102)
at org.apache.ibatis.cache.decorators.SerializedCache.putObject(SerializedCache.java:56)
at org.apache.ibatis.cache.decorators.LoggingCache.putObject(LoggingCache.java:51)
at org.apache.ibatis.cache.decorators.SynchronizedCache.putObject(SynchronizedCache.java:45)
at org.apache.ibatis.cache.decorators.TransactionalCache.flushPendingEntries(TransactionalCache.java:122)
at org.apache.ibatis.cache.decorators.TransactionalCache.commit(TransactionalCache.java:105)
…省略詳細異常棧
在這里,筆者疏漏了一點,那就是一個對象要通過二級緩存緩存的話,需要實現(xiàn)序列化。從異常信息中也可以看出這點。我們給實體加上實現(xiàn)序列化接口,滿心歡喜的再執(zhí)行一下:
DEBUG [main] - Cache Hit Ratio [com.hly.dao.CacheMapper]: 0.0
DEBUG [main] - ==> Preparing: SELECT * FROM tbl_employee where id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
查詢1完成
DEBUG [main] - Cache Hit Ratio [com.hly.dao.CacheMapper]: 0.0
DEBUG [main] - ==> Preparing: SELECT * FROM tbl_employee where id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
查詢2完成
e1與e2是否相等:false
這次是沒有報錯了,也打印了Cache Hit ...這樣的日志,說明二級緩存開啟了。但是,依然發(fā)送了兩條sql語句。這不符合預期呀。一番查證之后發(fā)現(xiàn),問題出現(xiàn)在getSession方法中:
public SqlSession getSession() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
return sqlSessionFactory.openSession();
}
可以看到,每次調用這個getSession方法時,會去讀配置文件,生成一個新的SqlSessionFactory導致沒有命中緩存。(這里是為什么呢?猜測是框架對不同的factory進行了緩存隔離,后面看源碼的時候驗證一下)修改getSession方法,一分為二:
/**
* 這種寫法在多線程下調用是有問題的
* @return
* @throws IOException
*/
public SqlSessionFactory initFactory() throws IOException{
if(sqlSessionFactory == null){
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
return sqlSessionFactory;
}
public SqlSession getSession() throws IOException {
initFactory();
System.out.println(sqlSessionFactory);
return this.sqlSessionFactory.openSession();
}
現(xiàn)在再執(zhí)行,就可以達到預期效果了:
DEBUG [main] - Cache Hit Ratio [com.hly.dao.CacheMapper]: 0.0
DEBUG [main] - ==> Preparing: SELECT * FROM tbl_employee where id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
查詢1完成
DEBUG [main] - Cache Hit Ratio [com.hly.dao.CacheMapper]: 0.5
查詢2完成
e1與e2是否相等:false
但是這個地方兩個對象是不相等的,留個疑問,后面看看源碼再說。
三、sqlSession失效的四種情況:
- 不同sqlSession
- sqlSession相同,查詢條件不同(當前sqlSession中還沒有這個緩存)
- sqlSession相同,兩次查詢之間執(zhí)行了增刪改操作
- sqlSession相同,手動清空了一級緩存中的內容(執(zhí)行了sqlSession.clearCache())
- 情況1: 不同sqlSession
@Test
public void testFirstLevelCacheFaild01(){
SqlSession sqlSession = null;
SqlSession sqlSession2 = null;
try{
sqlSession = getSession();
sqlSession2 = getSession();
CacheMapper mapper = sqlSession.getMapper(CacheMapper.class);
CacheMapper mapper2 = sqlSession2.getMapper(CacheMapper.class);
Employee e1 = mapper.testFirstLevelCache(1);
System.out.println("會話1查詢完畢");
Employee e2 = mapper2.testFirstLevelCache(1);
System.out.println("會話2查詢完畢");
boolean b = (e1 == e2);
System.out.println("e1與e2是否相等:" + b);
}catch(Exception e){
e.printStackTrace();
}finally{
sqlSession.close();
sqlSession2.close();
}
}
在測試方法中,打開了兩個sqlSession,并且執(zhí)行同樣的方法,同樣的參數(shù),效果如下。執(zhí)行了兩遍sql語句,返回的對象并不相等。
DEBUG [main] - ==> Preparing: SELECT * FROM tbl_employee where id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
會話1查詢完畢
DEBUG [main] - ==> Preparing: SELECT * FROM tbl_employee where id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
會話2查詢完畢
e1與e2是否相等:false
- 情況2:相同session,查詢條件不同
@Test
public void testFirstLevelCacheFailed02(){
SqlSession sqlSession = null;
try{
sqlSession = getSession();
CacheMapper mapper = sqlSession.getMapper(CacheMapper.class);
Employee e1 = mapper.testFirstLevelCache(1);
System.out.println("會話1查詢完畢");
Employee e2 = mapper.testFirstLevelCache(2);
System.out.println("會話2查詢完畢");
boolean b = (e1 == e2);
System.out.println("e1與e2是否相等:" + b);
}catch(Exception e){
e.printStackTrace();
}finally{
sqlSession.close();
}
}
查詢條件不同,是要發(fā)送兩個sql的:
DEBUG [main] - Cache Hit Ratio [com.hly.dao.CacheMapper]: 0.0
DEBUG [main] - ==> Preparing: SELECT * FROM tbl_employee where id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
會話1查詢完畢
DEBUG [main] - Cache Hit Ratio [com.hly.dao.CacheMapper]: 0.0
DEBUG [main] - ==> Preparing: SELECT * FROM tbl_employee where id=?
DEBUG [main] - ==> Parameters: 2(Integer)
DEBUG [main] - <== Total: 0
會話2查詢完畢
e1與e2是否相等:false
- 情況3:相同session但是兩次查詢之間進行了增刪改操作
測試代碼如下:
@Test
public void testFirstLevelCacheFailed03(){
SqlSession sqlSession = null;
try{
sqlSession = getSession();
CacheMapper mapper = sqlSession.getMapper(CacheMapper.class);
Employee e1 = mapper.testFirstLevelCache(1);
System.out.println("會話1查詢完畢");
e1.setName("修改用戶名");
mapper.updateEmp(e1);
System.out.println("修改完畢");
Employee e2 = mapper.testFirstLevelCache(2);
System.out.println("會話2查詢完畢");
boolean b = (e1 == e2);
System.out.println("e1與e2是否相等:" + b);
}catch(Exception e){
e.printStackTrace();
}finally{
sqlSession.close();
}
}
兩次查詢中間,加入了一條更新語句。執(zhí)行結果如下:
DEBUG [main] - Cache Hit Ratio [com.hly.dao.CacheMapper]: 0.0
DEBUG [main] - ==> Preparing: SELECT * FROM tbl_employee where id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
會話1查詢完畢
DEBUG [main] - ==> Preparing: UPDATE tbl_employee SET name=? WHERE id=?
DEBUG [main] - ==> Parameters: 修改用戶名(String), 1(Integer)
DEBUG [main] - <== Updates: 1
修改完畢
DEBUG [main] - Cache Hit Ratio [com.hly.dao.CacheMapper]: 0.0
DEBUG [main] - ==> Preparing: SELECT * FROM tbl_employee where id=?
DEBUG [main] - ==> Parameters: 2(Integer)
DEBUG [main] - <== Total: 0
會話2查詢完畢
e1與e2是否相等:false
可以看到,發(fā)送了三個sql語句。兩次查詢,雖說在同一個session內,且查詢條件也一樣,但由于兩次查詢之間有增刪改語句,所以緩存失效了。
- 情況4:相同session,但是手動執(zhí)行了sqlSession.clearCache()方法
@Test
public void testFirstLevelCacheFailed04(){
SqlSession sqlSession = null;
try{
sqlSession = getSession();
CacheMapper mapper = sqlSession.getMapper(CacheMapper.class);
Employee e1 = mapper.testFirstLevelCache(1);
System.out.println("會話1查詢完畢");
sqlSession.clearCache();
System.out.println("緩存clear完畢");
Employee e2 = mapper.testFirstLevelCache(2);
System.out.println("會話2查詢完畢");
boolean b = (e1 == e2);
System.out.println("e1與e2是否相等:" + b);
}catch(Exception e){
e.printStackTrace();
}finally{
sqlSession.close();
}
}
兩次查詢之間,手動調用clearCache,使一級緩存失效。結果符合預期。
DEBUG [main] - Cache Hit Ratio [com.hly.dao.CacheMapper]: 0.0
DEBUG [main] - ==> Preparing: SELECT * FROM tbl_employee where id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
會話1查詢完畢
緩存clear完畢
DEBUG [main] - Cache Hit Ratio [com.hly.dao.CacheMapper]: 0.0
DEBUG [main] - ==> Preparing: SELECT * FROM tbl_employee where id=?
DEBUG [main] - ==> Parameters: 2(Integer)
DEBUG [main] - <== Total: 0
會話2查詢完畢
e1與e2是否相等:false
四、二級緩存簡單原理
二級緩存:基于namspace的緩存
工作機制:
- 一個會話,查詢一條數(shù)據(jù),這個數(shù)據(jù)就會被放在當前會話的一級緩存中;
- 如果會話關閉,一級緩存中的數(shù)據(jù)會被保存到二級緩存中,新的會話查詢信息,就可以參照二級緩存中的內容;
- 如果sqlSession既有employee mapper查的employee對象,又有department mapper查詢的department對象:不同namespace查出的數(shù)據(jù)會放在自己對應的緩存map中。
使用步驟總結:
- 開啟全局二級緩存配置(cacheEnable)
- 去每個mapper.xml中配置使用二級緩存
- 我們的pojo需要實現(xiàn)序列化接口
五、緩存相關的設置和屬性:
- CacheEnabled(false時,二級緩存關閉)。
- 每個select標簽都有useCache=“true”,false的時候一級緩存依然可以使用,二級緩存不可用。
- 每個增刪改標簽的flushCache=“true”,增刪改執(zhí)行完成后就會清除緩存。
- sqlSession.clearCache()是否會影響二級緩存?不會的。。只是清除當前session的一級緩存。
- localCacheScope:本地緩存作用域(一級緩存)。可以通過將其值設置為STATEMENT來禁用一級緩存。