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" />