1. 程式人生 > >MyBatis Cache配置

MyBatis Cache配置

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>

如下:

from: https://www.cnblogs.com/jabnih/p/5705565.html