在mybatis中,開(kāi)發(fā)組織只提供了一些默認(rèn)的二級(jí)緩存實(shí)現(xiàn)的機(jī)制,并沒(méi)有直接內(nèi)置的支持OSCache和EHCache等二級(jí)緩存機(jī)制,而是作為一個(gè)集成jar包來(lái)提供二級(jí)緩存的實(shí)現(xiàn),在官方網(wǎng)站上我們可以找到mybatis-ehcache-1.0.1-bundle.zip,mybatis-oscache-1.0.1-bundle.zip等ehcache和oscache提供二級(jí)緩存的獨(dú)立工具包. 這里我就拿oscache在mybatis中的使用來(lái)舉例說(shuō)明:
1. 將mybatis-oscache-1.0.1-bundle.zip中涉及到的jar包放入到classpath路徑下
maven下可以這樣配置
<dependencies>
...
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-oscache</artifactId>
<version>1.0.2-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>opensymphony</groupId>
<artifactId>oscache</artifactId>
<version>2.4</version>
<exclusions>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
</dependency>
...
</dependencies>
2. 在mapper文件中的配置如下:
<mapper namespace="org.test.AuthMapper" >
<cache type="org.mybatis.caches.oscache.OSCache"/>
</mapper>
注意下面兩點(diǎn)
(a)在<select id="getAuth" parameterType="Map" resultType="Auth" useCache="false">中使用useCache="false"或useCache="true"來(lái)決定是否使用二級(jí)緩存。
(b)在增刪改中<insert id="insertAuth" parameterType="Auth" flushCache="true">使用flushCache="true"或flushCache="flase"來(lái)決定對(duì)這些進(jìn)行操作后清空該xml文件中所有查詢語(yǔ)句的二級(jí)緩存。
3. 在src目錄下創(chuàng)建一個(gè)oscache.properties的屬性文件,在里面指定緩存的各種屬性的設(shè)置:
cache.memory=true
cache.path=c:\\myapp\\cache
cache.persistence.class=com.opensymphony.oscache.plugins.diskpersistence.DiskPersistenceListener
cache.persistence.overflow.only=true
cache.capacity=100000