---
title: "iBATIS缓存的使用方法－－摘自iBATIS官方文档"
author: "addday"
date: "2009-04-08T11:49:36Z"
tags: []
slug: "ibatis-ibatis"
draft: false
lastmod: "2009-04-08T11:49:36Z"
id: 363463
url: "https://cardone.iteye.com/blog/363463"
---

iBATIS可以在Mapped Statement中使用缓存模型，在内存中缓存常用的数据。属性 cacheModel 定义查询 mapped statement 的缓存。每一个查询 mapped statement 可以使用不同或相同的cacheModel。以下给出个例子：

&lt;cacheModel id="product-cache" imlementation="LRU"&gt;  
 &lt;flushInterval hours="24"/&gt;  
 &lt;flushOnExecute statement="insertProduct"/&gt;  
 &lt;flushOnExecute statement="updateProduct"/&gt;  
 &lt;flushOnExecute statement="deleteProduct"/&gt;  
 &lt;property name="size" value="1000" /&gt;  
&lt;/cacheModel&gt;  
&lt;statement id="getProductList" parameterClass="int" cacheModel="product-cache"&gt;  
  select * from PRODUCT where PRD\_CAT\_ID = #value#  
&lt;/statement&gt;

 

上面例子中， “getProductList”的缓存使用 WEAK 引用类型，每 24 小时刷新一次，或当更新的操作发生时刷新。    
Cache Model 使用插件方式来支持不同的缓存算法。它的实现在 cacheModel 的用 type属性来指定（如上所示）。指定的实现类必须实现 CacheController接口，或是下面 4个别名中的其中之一。Cache Model 实现的其他配置参数通过 cacheModel的 property元素来设置。目前包括以下的 4 个实现：

1. "MEMORY” (com.ibatis.db.sqlmap.cache.memory.MemoryCacheController) 。MEMORY cache 实现使用 reference 类型来管理 cache 的行为。垃圾收集器可以根据 reference类型判断是否要回收 cache 中的数据。MEMORY实现适用于没有统一的对象重用模式的应用，或内存不足的应用。
2. “LRU” (com.ibatis.db.sqlmap.cache.lru.LruCacheController) 。LRU Cache 实现用“近期最少使用”原则来确定如何从 Cache 中清除对象。当 Cache溢出时，最近最少使用的对象将被从 Cache 中清除。使用这种方法，如果一个特定的对象总是被使用，它将保留在 Cache 中，而且被清除的可能性最小。对于在较长的期间内，某些用户经常使用某些特定对象的情况（例如，在 PaginatedList 和常用的查询关键字结果集中翻页） ，LRU Cache 是一个不错的选择。
3. “FIFO” (com.ibatis.db.sqlmap.cache.fifo.FifoCacheController) 。FIFO Cache 实现用“先进先出”原则来确定如何从 Cache 中清除对象。当 Cache 溢出时，最先进入 Cache 的对象将从 Cache 中清除。对于短时间内持续引用特定的查询而后很可能不再使用的情况，FIFO Cache 是很好的选择。
4. “OSCACHE” (com.ibatis.db.sqlmap.cache.oscache.OSCacheController)  。OSCACHE Cache 实现是OSCache2.0缓存引擎的一个 Plugin。它具有高度的可配置性，分布式，高度的灵活性。