像Hibernate一样,MyBatis也提供了缓存机制,一级缓存和二级缓存
一级缓存是在SqlSession的缓存,当Sqlsession关闭时,一级缓存也就结束了,一般在web应用中由于各种原因,一级缓存一般派不上用场
mybatis自身提供了二级缓存,需要在映射文件里加入<cache/>這個元素
根据官方文档:
我们必须配置一个元素在配置文件中
二级缓存是定义在Mapper级别的,离开了同一个Mapper namespace那么也就失效了
当然mybatis的二级缓存一般不能满足我们的需要,那么我们可以自定义缓存
这里以Ehcache为例子,我们要引入2个jar包
第二个包里已经提供了一个实现了cache接口的类了,然后我们需要在映射文件里配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="Mapper.StudentMapper">
<cache type="org.mybatis.caches.ehcache.EhcacheCache">
<property name="memoryStoreEvictionPolicy" value="LRU"/>
</cache>
<select id="selectOneStudent" resultType="Model.Student" useCache="true" flushCache="false">
select * from student where id =#{id}
</select>
</mapper>
我们还需要导入ehcache.xml配置文件,我翻了一下实现了cache接口的类的源码,里面有几个简单设置可以让我们去设置
下面给出相关源码:
/**
* Sets the time to idle for an element before it expires. Is only used if the element is not eternal.
*
* @param timeToIdleSeconds the default amount of time to live for an element from its last accessed or modified date
*/
public void setTimeToIdleSeconds(long timeToIdleSeconds) {
this.getCacheConfiguration().setTimeToIdleSeconds(timeToIdleSeconds);
}
/**
* Sets the time to idle for an element before it expires. Is only used if the element is not eternal.
*
* @param timeToLiveSeconds the default amount of time to live for an element from its creation date
*/
public void setTimeToLiveSeconds(long timeToLiveSeconds) {
this.getCacheConfiguration().setTimeToLiveSeconds(timeToLiveSeconds);
}
/**
* Sets the maximum objects to be held in memory (0 = no limit).
*
* @param maxElementsInMemory The maximum number of elements in memory, before they are evicted (0 == no limit)
*/
public void setMaxEntriesLocalHeap(long maxEntriesLocalHeap) {
this.getCacheConfiguration().setMaxEntriesLocalHeap(maxEntriesLocalHeap);
}
/**
* Sets the maximum number elements on Disk. 0 means unlimited.
*
* @param maxElementsOnDisk the maximum number of Elements to allow on the disk. 0 means unlimited.
*/
public void setMaxEntriesLocalDisk(long maxEntriesLocalDisk) {
this.getCacheConfiguration().setMaxEntriesLocalDisk(maxEntriesLocalDisk);
}
/**
* Sets the eviction policy. An invalid argument will set it to null.
*
* @param memoryStoreEvictionPolicy a String representation of the policy. One of "LRU", "LFU" or "FIFO".
*/
public void setMemoryStoreEvictionPolicy(String memoryStoreEvictionPolicy) {
this.getCacheConfiguration().setMemoryStoreEvictionPolicy(memoryStoreEvictionPolicy);
}
可以看看人家的注释!
对了,使用缓存的时候记得配置useCache 和 flushCache 2个属性
以下是百度上讲mybatis比较好的文章:
http://www.360doc.com/content/15/1205/07/29475794_518018352.shtml
http://blog.csdn.net/isea533/article/details/44566257