1. 程式人生 > >mybatis的二級快取的使用

mybatis的二級快取的使用

1.引入ehcache的jar包和mybatis整合ehcache的jar包;

        <!-- ehchache -->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>2.8.3</version>
        </dependency>
        <
dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-ehcache</artifactId> <version>1.0.0</version> </dependency>

2.配置ehcache.xml檔案:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false"
name="txswx-ehcache"> <diskStore path="java.io.tmpdir"/> <!-- DefaultCache setting. --> <defaultCache maxEntriesLocalHeap="10000" eternal="true" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" maxEntriesLocalDisk="100000"/> </ehcache>

3.mybatis-config.xml中開啟二級快取:<setting name="cacheEnabled" value="true"/>;

4.applicationContext.xml中配置ehcache的管理器;

<!-- Cache配置 -->
    <cache:annotation-driven cache-manager="cacheManager"/>
    <bean id="ehCacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
          p:configLocation="/WEB-INF/conf/ehcache.xml"/>
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
          p:cacheManager-ref="ehCacheManagerFactory"/>

5.*mapper.xml檔案中配置快取:

<cache type="org.mybatis.caches.ehcache.LoggingEhcache" > 
    <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>

這樣二級快取就起作用了。
不啟用快取:

修改statementuseCachefalse,表示該statement不再進行二級快取

<select id="getCountByName" parameterType="java.util.Map" resultType="INTEGER" statementType="CALLABLE" useCache="false">

 執行更新後,不重新整理二級快取:

<update id="updateUser" parameterType="cn.itcast.mybatis.po.User" flushCache="false">   
    update user set username = #{username},birthday = #{birthday},sex = #{sex} where id = #{id} 
  </update>