Mybatis缓存配置

来源:互联网 发布:淘宝首页下拉看懂电影 编辑:程序博客网 时间:2024/06/05 11:11

pom文件配置:

<dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.1</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.0</version></dependency><dependency><groupId>org.mybatis.caches</groupId><artifactId>mybatis-ehcache</artifactId><version>1.1.0</version></dependency><dependency><groupId>net.sf.ehcache</groupId><artifactId>ehcache-core</artifactId><version>2.5.3</version></dependency>


spring加载ehcache配置文件

<!-- 缓存管理器 --><bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"><property name="cacheManagerConfigFile" value="classpath:ehcache.xml" /></bean>

ehcache.xml:


<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="http://ehcache.xsd"><!--diskStore:缓存数据持久化的目录 地址 --><diskStore path="java.io.tmpdir" /><defaultCache maxElementsInMemory="1000"maxElementsOnDisk="10000000" eternal="false" overflowToDisk="false"diskPersistent="false" timeToIdleSeconds="120" timeToLiveSeconds="120"diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"></defaultCache></ehcache>

mybatis.xml开启缓存:

<settings><!-- 开启缓存 --><setting name="cacheEnabled" value="true" /><!-- 支持驼峰 --><setting name="mapUnderscoreToCamelCase" value="true" /><!-- lazyLoadingEnabled:延迟加载启动,默认是false --><setting name="lazyLoadingEnabled" value="false" /><!-- aggressiveLazyLoading:积极的懒加载,false的话按需加载,默认是true --><setting name="aggressiveLazyLoading" value="true" /></settings>


然后在对应的mapper.xml里面加上

<!-- 开启二级缓存 --><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>

(1)property参数配置不加也可以,都会有一个默认值,大家也可以查查一共有哪些配置,然后根据自己的需要来配置,然后这个配置是会带上cache执行的日志,如果不要带日志可以把LogginEhcache改成EhcacheCache。 
(2)如果readOnly为false,此时要结果集对象必须是可序列化的。需要将实体对象implements Serializable


上面这个是全局设置,在每条单独的sql语句上,还可以有局部设置,比如:

<select id="getOrder" parameterType="int" resultType="TOrder"  useCache="false">
        ...
</select>

useCache="false"表示该select语句不使用缓存(即使xml最开头的全局cache启用)

默认情况下,如果全局开启了缓存,insert/update/delete成功后,会自动刷新相关的缓存项,但有一点要特别注意:在mybatis与hibernate混用时,由于mybatis与hibernate的缓存是无关的,如果用mybatis做select查询,用hibernate做insert/update/delete,hibernate对数据的修改,并不会刷新mybatis的缓存。

1 0