1. 緩存
1.1 一級緩存
l Mybatis一級緩存默認存在的,不需要配置
l 一級緩存的生命週期爲Session的生命週期,如果session關閉,一級緩存消失
l 一級緩存,存儲的是對象的地址
1.2 二級緩存
第一步:在sqlMapConfig.xml中開啓二級緩存功能
<settings>
<setting name="cacheEnabled" value="true" />
</settings>
第二步:在sql映射文件中使用<cache/>標籤,指定當前文件中的sql語句可以使用緩存數據,也可以修改默認參數:
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
第三步:在<select>標籤中使用useCache指定當前sql語句是否使用緩存數據
1.3 Ehcache緩存
第一步:導入Ehcache相關jar包
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
第二步:在項目的類路徑下提供Ehcache的核心配置文件ehcache.xml,可以從Ehcache的核心jar包中獲得
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<diskStore path="java.io.tmpdir" />
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120" maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap" />
</defaultCache>
</ehcache>
第三步:修改sql映射文件中的<cache>標籤
<cache type="org.mybatis.caches.ehcache.EhcacheCache" />