MyBatis Cache配置

MyBatis提供了一级缓存和二级缓存

配置

全局配置

配置

说明

默认值

可选值

cacheEnabled

全局缓存的开关

true

true false

localCacheScope

本地缓存,SESSION表示执行的sql结果缓存数据可以在同一个sqlSession共享,

而STATEMENT,则同只有在单条语句会被缓存,

两条语句不能共享缓存数据

SESSION

SESSION STATEMENT

    <!-- 默认值 -->
<setting name="cacheEnabled" value="true"/>
<setting name="cacheEnabled" value="SESSION"/>


Mapper配置

flushCache=true表示该语句的执行结果,会清空本地缓存以及2级缓存
useCache="true"表示该语句的执行结果,会被缓存到到2级缓存
默认值:
<select flushCache="false" useCache="true">
<insert/update/delete flushCache="true">

<cache>:当前Mapper的缓存配置,二级缓存
<cache-ref>:cache只对特定的Namespace使用,即每个namespace使用一个cache实例,如果要多个namespace使用同一个cache实例,则可以使用cache-ref来引用

<cache blocking="" eviction="" flushInterval="" readOnly="" size="" type="">
<property name="" value=""/>
</cache>
<cache-ref namespace=""/>


cache配置

属性

说明

默认值

可选值

eviction

回收内存策略

LRU

LRU FIFO SOFT WEAK

flushInterval

刷新间隔

没设置

大于0 (单位:ms)

size

缓存对象的数量

1024

大于0

readOnly

如果为true会返回所有调用者同一个实例,尽管提高了性能,

但是需要程序保证实例对象不被修改,如果为false,

则为读写缓存,会通过序列化返回缓存对象的一份Copy,

较慢,但是比较安全

false

true false

type

可以指定自定义缓存,但是该类必须实现

org.apache.ibatis.cache.Cache接口

 

com....class

自定义缓存
<!-- 该属性会调用setCacheFile方法(setter),将属性值注入 -->
<cache type="com.domain.something.MyCustomCache">
<property name="cacheFile" value="/tmp/my-custom-cache.tmp"/>
</cache>


二级缓存整体管理结构:

MapperA.xml

<mapper namespace="com.jabnih.demo.mapper.MapperA">
<cache />
</mapper>


MapperB.xml

<mapper namespace="com.jabnih.demo.mapper.MapperB">
<cache-ref namespace="com.jabnih.demo.mapper.MapperA"/>
</mapper>


MapperC.xml

<mapper namespace="com.jabnih.demo.mapper.MapperC">
<cache />
</mapper>


如下: