1、一級緩存(SqlSession)
一級緩存的作用域是同一個SqlSession,在同一個sqlSession中兩次執行相同的sql語句,第一次執行完畢會将資料庫中查詢的資料寫到緩存(記憶體),第二次會從緩存中擷取資料将不再從資料庫查詢,進而提高查詢效率。當一個sqlSession結束後該sqlSession中的一級緩存也就不存在了。若sqlSession執行了commit操作(insert、update、delete),會清空緩存,避免讀髒資料,存儲最新的資訊。Mybatis預設開啟一級緩存。
當spring和mybaits整合後,事務掌握在service中,若執行兩次查詢相同的資訊,不走一級緩存,因為service結束後,sqlSession就關閉,一級緩存就清空。
2、二級緩存(Mapper)
二級緩存是mapper級别的緩存,多個SqlSession去操作同一個Mapper的sql語句,多個SqlSession去操作資料庫得到資料會存在二級緩存區域,多個SqlSession可以共用二級緩存,二級緩存是跨SqlSession的。二級緩存是多個SqlSession共享的,其作用域是mapper的同一個namespace,不同的sqlSession兩次執行相同namespace下的sql語句且向sql中傳遞參數也相同即最終執行相同的sql語句,第一次執行完畢會将資料庫中查詢的資料寫到緩存(記憶體),第二次會從緩存中擷取資料将不再從資料庫查詢,進而提高查詢效率。但是mybatis預設開啟的二級緩存預設實作類是一個記憶體級别的,不建議使用,是以我們要配置第三方緩存架構ehcache:
porm.xml
<!-- ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.1</version>
</dependency>
<!-- mybatis-ehcache -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.0.0</version>
</dependency>
在Configuration.xml檔案中加入
<setting name="cacheEnabled" value="true"/>
在對應的Mapper.xml中加入
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
建立ehcache.xml檔案
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<diskStore path="C:\cache"/>
<defaultCache
maxElementsInMemory="3000"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="3600"
overflowToDisk="true"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="100"
memoryStoreEvictionPolicy="LRU"
/>
<cache name="userCache"
maxElementsInMemory="3000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="3600"
timeToLiveSeconds="3600"
memoryStoreEvictionPolicy="LFU"
/>
</ehcache>
3、重新整理緩存
在mapper的同一個namespace中,如果有其它insert、update、delete操作資料後需要重新整理緩存,如果不執行重新整理緩存會髒讀資料。
設定statement配置中flushCache屬性,預設為true即重新整理緩存,如果改成false則不會重新整理。使用緩存時如果手動修改資料庫表中的查詢資料會出現髒讀。
參考:http://www.360doc.com/content/15/1205/07/29475794_518018352.shtml