Mybatis緩存機制
一.什麼是Mybatis的緩存機制
緩存的概念簡而言之就是臨時存放在本機的數據。爲什麼需要緩存機制呢,因爲鏈接數據庫的資源很珍貴,而且如果每次查詢數據都需要訪問數據庫的話會很費時,且效率不高,於是就有了緩存的機制。有了緩存機制,由原來的 請求-->數據庫 到 請求-->緩存(是否有數據? 數據:請求數據庫).
Mybatis分兩級緩存:爲一級緩存和二級緩存!
1.一級緩存
一級緩存是基於 PerpetualCache(mybatis自帶)的 HashMap本地緩存,作用範圍爲session,session是一次會話(從請求到訪問數據庫到返回數據,直至請求結束稱之爲一次會話),所以當session commit或cleanCache後,緩存就會被清空.一級緩存是Mybatis自帶,並自動開啓的。其數據存儲關係如下圖:
測試代碼:
Users user=session.selectOne(sql,1); // session.commit(); //提交兩個sql 執行,否則一個 sql Users user1=session.selectOne(sql,1); 兩條sql System.out.println(user.getName());
結果:DEBUG - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter. DEBUG - PooledDataSource forcefully closed/removed all connections. DEBUG - PooledDataSource forcefully closed/removed all connections. DEBUG - PooledDataSource forcefully closed/removed all connections. DEBUG - PooledDataSource forcefully closed/removed all connections. DEBUG - Opening JDBC Connection DEBUG - Created connection 1725097945. DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@66d2e7d9] DEBUG - ==> Preparing: select o.*,u.name,u.age from users u join myorder o on o.id=u.id where o.id=? DEBUG - ==> Parameters: 1(Integer) DEBUG - <== Total: 1
2.二級緩存
二級緩存緩存的是結果對象,獨立於session,作用範圍爲所有namespace定義的方法,其存儲在Mybatis中的內存空間中,作用結構圖如下:
二級緩存需要自己配置並開啓,需要走三大步:
一.在config配置文件加入如下代碼(開啓緩存):
<settings> <setting name="cacheEnabled" value="true"/> </settings>
二.在mapper映射文件中加入便籤:
1.最簡單寫法:
<cache/>
2.帶點參數eviction是驅逐,FIFO是先進先出分方式,flushInterval是刷新的間隔以秒爲單位。
<cache eviction="FIFO" flushInterval="2000" size="512" readOnly="true" />
三.編寫代碼,完了後session一定要commit無論是查還是增刪改。
3.一級緩存與二級緩存的區分
1.一級緩存緩存在session內部,與session息息相關,二級緩存獨立於session,作用範圍爲整個namespace
2.一級緩存是自動開啓的,二級緩存要實現3大步驟,手動開啓
3.一級緩存存在session中,當session調用commit或cleanCache數據就會被清除,二級緩存存在Mybatis的內存中,不受影響,只有當虛擬機被關閉纔會丟失數據.
結語:每個人都會有一段孤獨的時間,或長或短,我只是選擇了最長的那條路!!!