<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-ehcache</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>${ehcache.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency>
二、添加ehcache的配置:ehcache.xml
<ehcache updateCheck="true" name="application-cache"> <diskStore path="java.io.tmpdir"/> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" /> </ehcache>
三、在spring配置文件 application-context.xml中添加配置:
beans头中添加引用:
xmlns:p="http://www.springframework.org/schema/p" xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation中添加
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
添加ehcache的bean:
<cache:annotation-driven/> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cacheManager-ref="ehcache"/> <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:configLocation="classpath:ehcache.xml" p:shared="true"/>
四、修改mybatis-config.xml:
添加:
<!-- 全局映射器启用缓存 --> <setting name="cacheEnabled" value="true"/>
该步骤也可以省略,mybatis默认cacheEnable是打开的
五、在需要使用缓存的mapper中添加:
<cache type="org.mybatis.caches.ehcache.LoggingEhcache"/> <!--<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>-->
实测中没发现这两者有什么区别。相关资料说LogginEhcache打开了日志。