【mybatis】之四:mybatis緩存機制

一、概要

mybatis的緩存分為一級緩存和二級緩存。一級緩存是本地緩存,SqlSession級別的。二級緩存是全局緩存。

二、緩存體驗

  1. 一級緩存體驗
    @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提供的一級緩存。

  1. 二級緩存體驗

二級緩存是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失效的四種情況:

  1. 不同sqlSession
  2. sqlSession相同,查詢條件不同(當前sqlSession中還沒有這個緩存)
  3. sqlSession相同,兩次查詢之間執(zhí)行了增刪改操作
  4. 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的緩存

工作機制:

  1. 一個會話,查詢一條數(shù)據(jù),這個數(shù)據(jù)就會被放在當前會話的一級緩存中;
  2. 如果會話關閉,一級緩存中的數(shù)據(jù)會被保存到二級緩存中,新的會話查詢信息,就可以參照二級緩存中的內容;
  3. 如果sqlSession既有employee mapper查的employee對象,又有department mapper查詢的department對象:不同namespace查出的數(shù)據(jù)會放在自己對應的緩存map中。

使用步驟總結:

  1. 開啟全局二級緩存配置(cacheEnable)
  2. 去每個mapper.xml中配置使用二級緩存
  3. 我們的pojo需要實現(xiàn)序列化接口

五、緩存相關的設置和屬性:

  1. CacheEnabled(false時,二級緩存關閉)。
  2. 每個select標簽都有useCache=“true”,false的時候一級緩存依然可以使用,二級緩存不可用。
  3. 每個增刪改標簽的flushCache=“true”,增刪改執(zhí)行完成后就會清除緩存。
  4. sqlSession.clearCache()是否會影響二級緩存?不會的。。只是清除當前session的一級緩存。
  5. localCacheScope:本地緩存作用域(一級緩存)。可以通過將其值設置為STATEMENT來禁用一級緩存。
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,702評論 6 534
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,615評論 3 419
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,606評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,044評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,826評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,227評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,307評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,447評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,992評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,807評論 3 355
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,001評論 1 370
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,550評論 5 361
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,243評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,667評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,930評論 1 287
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,709評論 3 393
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,996評論 2 374

推薦閱讀更多精彩內容