MyBaits毕竟是对数据库操作的框架,对缓存不大专业,所以留有对第三方缓存框架整合的接口提供使用
参考文档http://www.mybatis.org/ehcache-cache/
添加依赖
<!--Ehcache-->
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.5</version>
</dependency>
添加ehcache.xml(你写错文件名字,它就使用默认的mybaits自己的缓存!不会生产文件夹,控制台会提示:
代表它依旧用的是ehcache-failsafe里的)
<?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="D:\ehcache"/>
<!-- 默认缓存配置 -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
</ehcache>
关于引入xsd的url,可以
打开settings->languages&frameworks->schemas and dtds ,添加地址 http://ehcache.org/ehcache.xsd
在需要配置的Mapper里添加配置<property>可以不写……
<mapper namespace="com.yiki.Dao.DepartmentMapper">
<!--使用第三方缓存框架
-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache">
<property name="timeToIdleSeconds" value="3600"/><!--1 hour-->
<property name="timeToLiveSeconds" value="3600"/><!--1 hour-->
<property name="maxEntriesLocalHeap" value="1000"/>
<property name="maxEntriesLocalDisk" value="10000000"/>
<property name="memoryStoreEvictionPolicy" value="LRU"/>
</cache>
测试生成缓存代表成功
测试
public void test8() throws IOException {
start();
System.out.println(d_mapper.getDeptById(1));
System.out.println(d_mapper.getDeptById(1));
System.out.println(d_mapper.getDeptById(1));
sqlSession.close();
}