mybatis一級緩存二級緩存

一級緩存

  Mybatis對緩存提供支持,但是在沒有配置的默認情況下,它只開啟一級緩存,一級緩存只是相對于同一個SqlSession而言。所以在參數和SQL完全一樣的情況下,我們使用同一個SqlSession對象調用一個Mapper方法,往往只執行一次SQL,因為使用SelSession第一次查詢后,MyBatis會將其放在緩存中,以后再查詢的時候,如果沒有聲明需要刷新,并且緩存沒有超時的情況下,SqlSession都會取出當前緩存的數據,而不會再次發送SQL到數據庫。

              

  為什么要使用一級緩存,不用多說也知道個大概。但是還有幾個問題我們要注意一下。

  1、一級緩存的生命周期有多長?

  a、MyBatis在開啟一個數據庫會話時,會 創建一個新的SqlSession對象,SqlSession對象中會有一個新的Executor對象。Executor對象中持有一個新的PerpetualCache對象;當會話結束時,SqlSession對象及其內部的Executor對象還有PerpetualCache對象也一并釋放掉。

  b、如果SqlSession調用了close()方法,會釋放掉一級緩存PerpetualCache對象,一級緩存將不可用。

  c、如果SqlSession調用了clearCache(),會清空PerpetualCache對象中的數據,但是該對象仍可使用。

  d、SqlSession中執行了任何一個update操作(update()、delete()、insert()) ,都會清空PerpetualCache對象的數據,但是該對象可以繼續使用

 ? ?2、怎么判斷某兩次查詢是完全相同的查詢?

  mybatis認為,對于兩次查詢,如果以下條件都完全一樣,那么就認為它們是完全相同的兩次查詢。

  2.1 傳入的statementId

  2.2 查詢時要求的結果集中的結果范圍

  2.3. 這次查詢所產生的最終要傳遞給JDBC java.sql.Preparedstatement的Sql語句字符串(boundSql.getSql()?)

  2.4?傳遞給java.sql.Statement要設置的參數值

二級緩存:

  MyBatis的二級緩存是Application級別的緩存,它可以提高對數據庫查詢的效率,以提高應用的性能。

  MyBatis的緩存機制整體設計以及二級緩存的工作模式

  

?

  SqlSessionFactory層面上的二級緩存默認是不開啟的,二級緩存的開席需要進行配置,實現二級緩存的時候,MyBatis要求返回的POJO必須是可序列化的。 也就是要求實現Serializable接口,配置方法很簡單,只需要在映射XML文件配置就可以開啟緩存了<cache/>,如果我們配置了二級緩存就意味著:

  • 映射語句文件中的所有select語句將會被緩存。
  • 映射語句文件中的所欲insert、update和delete語句會刷新緩存。
  • 緩存會使用默認的Least Recently Used(LRU,最近最少使用的)算法來收回。
  • 根據時間表,比如No Flush Interval,(CNFI沒有刷新間隔),緩存不會以任何時間順序來刷新。
  • 緩存會存儲列表集合或對象(無論查詢方法返回什么)的1024個引用
  • 緩存會被視為是read/write(可讀/可寫)的緩存,意味著對象檢索不是共享的,而且可以安全的被調用者修改,不干擾其他調用者或線程所做的潛在修改。

實踐:

一、創建一個POJO Bean并序列化

  由于二級緩存的數據不一定都是存儲到內存中,它的存儲介質多種多樣,所以需要給緩存的對象執行序列化。(如果存儲在內存中的話,實測不序列化也可以的。)

package com.yihaomen.mybatis.model;import com.yihaomen.mybatis.enums.Gender;
import java.io.Serializable;
import java.util.List;/*** ?@ProjectName:?springmvc-mybatis?*/
public class Student implements Serializable{private static final long serialVersionUID = 735655488285535299L;private String id;private String name;private int age;private Gender gender;private List<Teacher> teachers;
setters
&getters()....;toString(); }

?

?二、在映射文件中開啟二級緩存

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yihaomen.mybatis.dao.StudentMapper"><!--開啟本mapper的namespace下的二級緩存--><!--eviction:代表的是緩存回收策略,目前MyBatis提供以下策略。(1) LRU,最近最少使用的,一處最長時間不用的對象(2) FIFO,先進先出,按對象進入緩存的順序來移除他們(3) SOFT,軟引用,移除基于垃圾回收器狀態和軟引用規則的對象(4) WEAK,弱引用,更積極的移除基于垃圾收集器狀態和弱引用規則的對象。這里采用的是LRU,移除最長時間不用的對形象flushInterval:刷新間隔時間,單位為毫秒,這里配置的是100秒刷新,如果你不配置它,那么當SQL被執行的時候才會去刷新緩存。size:引用數目,一個正整數,代表緩存最多可以存儲多少個對象,不宜設置過大。設置過大會導致內存溢出。這里配置的是1024個對象readOnly:只讀,意味著緩存數據只能讀取而不能修改,這樣設置的好處是我們可以快速讀取緩存,缺點是我們沒有辦法修改緩存,他的默認值是false,不允許我們修改--><cache eviction="LRU" flushInterval="100000" readOnly="true" size="1024"/><resultMap id="studentMap" type="Student"><id property="id" column="id" /><result property="name" column="name" /><result property="age" column="age" /><result property="gender" column="gender" typeHandler="org.apache.ibatis.type.EnumOrdinalTypeHandler" /></resultMap><resultMap id="collectionMap" type="Student" extends="studentMap"><collection property="teachers" ofType="Teacher"><id property="id" column="teach_id" /><result property="name" column="tname"/><result property="gender" column="tgender" typeHandler="org.apache.ibatis.type.EnumOrdinalTypeHandler"/><result property="subject" column="tsubject" typeHandler="org.apache.ibatis.type.EnumTypeHandler"/><result property="degree" column="tdegree" javaType="string" jdbcType="VARCHAR"/></collection></resultMap><select id="selectStudents" resultMap="collectionMap">SELECTs.id, s.name, s.gender, t.id teach_id, t.name tname, t.gender tgender, t.subject tsubject, t.degree tdegreeFROMstudent sLEFT JOINstu_teach_rel strONs.id = str.stu_idLEFT JOINteacher tONt.id = str.teach_id</select><!--可以通過設置useCache來規定這個sql是否開啟緩存,ture是開啟,false是關閉--><select id="selectAllStudents" resultMap="studentMap" useCache="true">SELECT id, name, age FROM student</select><!--刷新二級緩存<select id="selectAllStudents" resultMap="studentMap" flushCache="true">SELECT id, name, age FROM student</select>-->
</mapper>

?

三、在 mybatis-config.xml中開啟二級緩存

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><settings><!--這個配置使全局的映射器(二級緩存)啟用或禁用緩存--><setting name="cacheEnabled" value="true" />.....</settings>....
</configuration>

?

四、測試

package com.yihaomen.service.student;import com.yihaomen.mybatis.dao.StudentMapper;
import com.yihaomen.mybatis.model.Student;
import com.yihaomen.mybatis.model.Teacher;
import com.yihaomen.service.BaseTest;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.List;/*** ??* ?@ProjectName:?springmvc-mybatis?*/
public class TestStudent extends BaseTest {public static void selectAllStudent() {SqlSessionFactory sqlSessionFactory = getSession();SqlSession session = sqlSessionFactory.openSession();StudentMapper mapper = session.getMapper(StudentMapper.class);List<Student> list = mapper.selectAllStudents();System.out.println(list);System.out.println("第二次執行");List<Student> list2 = mapper.selectAllStudents();System.out.println(list2);session.commit();System.out.println("二級緩存觀測點");SqlSession session2 = sqlSessionFactory.openSession();StudentMapper mapper2 = session2.getMapper(StudentMapper.class);List<Student> list3 = mapper2.selectAllStudents();System.out.println(list3);System.out.println("第二次執行");List<Student> list4 = mapper2.selectAllStudents();System.out.println(list4);session2.commit();}public static void main(String[] args) {selectAllStudent();}
}

?

結果:

[QC] DEBUG [main] org.apache.ibatis.transaction.jdbc.JdbcTransaction.setDesiredAutoCommit(98) | Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@51e0173d]
[QC] DEBUG [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(139) | ==> Preparing: SELECT id, name, age FROM student
[QC] DEBUG [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(139) | ==> Parameters:
[QC] DEBUG [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(139) | <== Total: 6
[Student{id='1', name='劉德華', age=55, gender=null, teachers=null}, Student{id='2', name='張惠妹', age=49, gender=null, teachers=null}, Student{id='3', name='謝霆鋒', age=35, gender=null, teachers=null}, Student{id='4', name='王菲', age=47, gender=null, teachers=null}, Student{id='5', name='汪峰', age=48, gender=null, teachers=null}, Student{id='6', name='章子怡', age=36, gender=null, teachers=null}]
第二次執行
[QC] DEBUG [main] org.apache.ibatis.cache.decorators.LoggingCache.getObject(62) | Cache Hit Ratio [com.yihaomen.mybatis.dao.StudentMapper]: 0.0
[Student{id='1', name='劉德華', age=55, gender=null, teachers=null}, Student{id='2', name='張惠妹', age=49, gender=null, teachers=null}, Student{id='3', name='謝霆鋒', age=35, gender=null, teachers=null}, Student{id='4', name='王菲', age=47, gender=null, teachers=null}, Student{id='5', name='汪峰', age=48, gender=null, teachers=null}, Student{id='6', name='章子怡', age=36, gender=null, teachers=null}]
二級緩存觀測點
[QC] DEBUG [main] org.apache.ibatis.cache.decorators.LoggingCache.getObject(62) | Cache Hit Ratio [com.yihaomen.mybatis.dao.StudentMapper]: 0.3333333333333333
[Student{id='1', name='劉德華', age=55, gender=null, teachers=null}, Student{id='2', name='張惠妹', age=49, gender=null, teachers=null}, Student{id='3', name='謝霆鋒', age=35, gender=null, teachers=null}, Student{id='4', name='王菲', age=47, gender=null, teachers=null}, Student{id='5', name='汪峰', age=48, gender=null, teachers=null}, Student{id='6', name='章子怡', age=36, gender=null, teachers=null}]
第二次執行
[QC] DEBUG [main] org.apache.ibatis.cache.decorators.LoggingCache.getObject(62) | Cache Hit Ratio [com.yihaomen.mybatis.dao.StudentMapper]: 0.5
[Student{id='1', name='劉德華', age=55, gender=null, teachers=null}, Student{id='2', name='張惠妹', age=49, gender=null, teachers=null}, Student{id='3', name='謝霆鋒', age=35, gender=null, teachers=null}, Student{id='4', name='王菲', age=47, gender=null, teachers=null}, Student{id='5', name='汪峰', age=48, gender=null, teachers=null}, Student{id='6', name='章子怡', age=36, gender=null, teachers=null}]

Process finished with exit code 0

?

我們可以從結果看到,sql只執行了一次,證明我們的二級緩存生效了。

?

https://gitee.com/huayicompany/springmvc-mybatis

參考:

[1]楊開振 著,《深入淺出MyBatis技術原理與實戰》, 電子工業出版社,2016.09

[2]博客,http://blog.csdn.net/luanlouis/article/details/41280959

[3]博客,http://www.cnblogs.com/QQParadise/articles/5109633.html

[4]博客,http://blog.csdn.net/isea533/article/details/44566257

轉載于:https://www.cnblogs.com/happyflyingpig/p/7739749.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/253030.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/253030.shtml
英文地址,請注明出處:http://en.pswp.cn/news/253030.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

CMOS Sensor的調試分享

目前&#xff0c;包括移動設備在內的很多多媒體設備上都使用了攝像頭&#xff0c;而且還在以很快的速度更新換代。目前使用的攝像頭分為兩種&#xff1a;CCD(Charge Couple Device電荷偶合器件)和 CMOS(Complementary Metal Oxide Semiconductor互補金屬氧化物半導體)。這兩種各…

利用反射修改final數據域

當final修飾一個數據域時&#xff0c;意義是聲明該數據域是最終的&#xff0c;不可修改的。常見的使用場景就是eclipse自動生成的serialVersionUID一般都是final的。 另外還可以構造線程安全&#xff08;thread safe&#xff09;的immutable類&#xff0c;比如String&#xff0…

mysql簡單創建數據庫權限(待修改備注)

CREATE DATABASE web DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;一、環境&#xff1a;CentOS 6.8mysql 5.6二、背景給外包的工作人員提供我司某臺服務器的 mysql 中某個數據庫的訪問權限。之所以要做限制&#xff0c;是防止他們對我司其他的數據庫非法進行操作。三、…

Centos 能ping通域名和公網ip但是網站不能夠打開,服務器拒絕了請求。打開80端口解決。...

博客搬遷&#xff0c;給你帶來的不便&#xff0c;敬請諒解&#xff01; http://www.suanliutudousi.com/2017/10/29/centos-%E8%83%BDping%E9%80%9A%E5%9F%9F%E5%90%8D%E5%92%8C%E5%85%AC%E7%BD%91ip%E4%BD%86%E6%98%AF%E7%BD%91%E7%AB%99%E4%B8%8D%E8%83%BD%E5%A4%9F%E6%89%93…

ISP 圖像傳感器camera原理

1、Color Filter Array — CFA 隨著數碼相機、手機的普及&#xff0c;CCD/CMOS 圖像傳感器近年來得到廣泛的關注和應用。 圖像傳感器一般都采用一定的模式來采集圖像數據&#xff0c;常用的有 BGR 模式和 CFA 模式。BGR 模式是一種可直接進行顯示和壓縮等處理的圖像數據模式&am…

51nod 1027 大數乘法

1027 大數乘法基準時間限制&#xff1a;1 秒 空間限制&#xff1a;131072 KB 分值: 0 難度&#xff1a;基礎題收藏關注給出2個大整數A,B&#xff0c;計算A*B的結果。 Input第1行&#xff1a;大數A 第2行&#xff1a;大數B (A,B的長度 < 1000&#xff0c;A,B > 0&#xff…

file mmap

do_set_pmd統計參數只會在這里設置&#xff1a; add_mm_counter(vma->vm_mm, MM_FILEPAGES, HPAGE_PMD_NR);但是這貌似都是處理大頁的情況哪&#xff0c;小頁呢&#xff1f; alloc_set_pte中有函數&#xff1a;inc_mm_couter_fast(vma->vm_mm, mm_couter_file(page)&…

Linux鏈接庫三(C跟C++之間動態庫的相互調用)

http://www.cppblog.com/wolf/articles/74928.html http://www.cppblog.com/wolf/articles/77828.html http://www.jb51.net/article/34990.htm C和C之間庫的互相調用 extern "C"的理解&#xff1a; 很多人認為"C"表示的C語言&#xff0c;實際并非如此&…

C#如何開發多語言支持的Winform程序

C# Winform項目多語言實現(支持簡/繁/英三種語言)有很多種方案實現多語言&#xff0c;我在這里介紹一種最簡單最容易理解的&#xff0c;作為教學材題應該從通俗易懂入手。在寫這篇文章之前&#xff0c;本來想用枚舉窗體對象成員的方式設置語言&#xff0c;但是找不到源代碼了&a…

Alpha 沖刺 (2/10)

Alpha 沖刺 &#xff08;2/10&#xff09; 隊名&#xff1a;第三視角 組長博客鏈接 本次作業鏈接 團隊部分 團隊燃盡圖 工作情況匯報 張揚&#xff08;組長&#xff09; 過去兩天完成了哪些任務&#xff1a; 文字/口頭描述&#xff1a; 1、學習qqbot庫&#xff1b; 2、實時保存…

Linux學習之第二課時--linux命令格式及命令概述

命令概述 Linux提供了大量的命令&#xff0c;利用它可以有效地完成大量的工作&#xff0c;如磁盤管理&#xff0c;文件存取&#xff0c;目錄操作&#xff0c;進程管理&#xff0c;文件權限設定等 Linux命令格式 Linux命令的組成部分&#xff1a;命令字 命令選項參數&#xff…

Linux C語言調用C++動態鏈接庫

Linux C語言調用C動態鏈接庫 標簽&#xff1a; C調用C庫 2014-03-10 22:56 3744人閱讀 評論(0) 收藏 舉報 分類&#xff1a; 【Linux應用開發】&#xff08;48&#xff09; 版權聲明&#xff1a;本文為博主原創文章&#xff0c;未經博主允許不得轉載。 如果你有一個c做的動態…

Android實踐 -- 對apk進行系統簽名

對apk進行系統簽名 簽名工具 網盤下載 &#xff0c;需要Android系統的簽名的文件platform.x509.pem 和 platform.pk8 這個兩個文件在Android源碼中的 ./build/target/product/security 目錄下 具體的使用方法&#xff1a; java -jar signapk.jar platform.x509.pem platform.…

Java編寫基于netty的RPC框架

一 簡單概念RPC: ( Remote Procedure Call),遠程調用過程,是通過網絡調用遠程計算機的進程中某個方法,從而獲取到想要的數據,過程如同調用本地的方法一樣.阻塞IO :當阻塞I/O在調用InputStream.read()方法是阻塞的,一直等到數據到來時才返回,同樣ServerSocket.accept()方法時,也…

linux下c和c++互相調用

c調用cpp 創建個目錄 創建4個文件 c.c--c文件 cpp.cpp--c文件 cpp.hh--c聲明文件 Makefile c.c [javascript] view plaincopy#include "cpp.hh" int main() { cpp_fun(); } cpp.cpp [cpp] view plaincopy#include "cpp.hh" #include <stdi…

Applications Manager Docker監控

Docker 是一個流行的開源容器應用程序&#xff0c;允許您將應用程序、應用程序的內部依賴和關聯庫打包到一個單元中。Docker 的主要優點在于單臺機器上的多個 docker 容器共享同一操作系統內核&#xff0c;這可以幫助提升性能和節省大量內存。監控 docker 容器會很困難&#xf…

find

Linux中find常見用法示例 find path -option [ -print ] [ -exec -ok command ] {} \; find命令的參數&#xff1b; pathname: find命令所查找的目錄路徑。例如用.來表示當前目錄&#xff0c;用/來表示系統根目錄。-print&#xff1a; find命令將匹配的文件輸出…

PHP將多個文件中的內容合并為新的文件

function test(){$hostdir iconv("utf-8","gbk","C:\Users\原萬里\Desktop\日常筆記") ; //iconv()轉換編碼方式&#xff0c;將UTF-8轉換為gbk&#xff0c;若是報錯在gbk后加//IGNORE$filesnames scandir($hostdir); …

HTTP Live Streaming直播(iOS直播)技術分析與實現

不經意間發現&#xff0c;大半年沒寫博客了&#xff0c;自覺汗顏。實則2012后半年&#xff0c;家中的事一樣接著一樣發生&#xff0c;實在是沒有時間。快過年了&#xff0c;總算忙里偷閑&#xff0c;把最近的一些技術成果&#xff0c;總結成了文章&#xff0c;與大家分享。 前些…

中文論文格式【雜】

轉自知乎&#xff0c;https://www.zhihu.com/question/23791742/answer/344752056 【紙張】畢業論文一律打印&#xff0c;采取A4紙張&#xff0c;頁邊距一律采取&#xff1a;上、下2.5cm&#xff0c;左3cm,右1.5cm&#xff0c;行間距取多倍行距(設置值為1.25);字符間距為默認值…