在IBatis中提供了資料庫緩衝的模式,可以提高訪問效率。對於一些不常更新的表可以直接利用IBatis的緩衝方式。
要使用IBatis的資料庫緩衝,只要利用設定檔就可以了,實現起來比較簡單:
<select id="GetCachedAccountsViaResultMap"
resultMap="account-result"
cacheModel="account-cache" >
select *
from Accounts
order by Account_ID
</select>
最主要的就是cacheModel="account-cache",指定緩衝的方式,如下,是具體配置緩衝的地方: <cacheModels>
<cacheModel id="account-cache" implementation="MEMORY" >
<flushInterval hours="24"/>
<flushOnExecute statement="UpdateAccountViaInlineParameters"/>
<flushOnExecute statement="UpdateAccountViaParameterMap"/>
<flushOnExecute statement="InsertAccountViaParameterMap"/>
<property name="Type" value="Weak"/>
</cacheModel>
</cacheModels>
其中:implementation="MEMORY"是設定緩衝的實現方式,可以指定LRU、FIFO等,有點類似於記憶體的頁替換策略。MEMORY是最常使用的一種方式。
flushOnExecute設定的是當執行了這些語句時更新緩衝。
配置好之後我進行了一個簡單的測試,基本上是可以的,但也有一點問題:
1、第一次查詢結果是4條記錄,當我手工往資料庫中插入一條記錄時,第二次查詢還是4條記錄
2、當我把系統時間改成第二天(24小時後),再查,得到的結果是5條記錄
3、當我執行了InsertAccountViaParameterMap語句插入一條記錄時,再查詢得到的是6條記錄
也就是說:當系統中的表從不進行手工維護,也不由第三方程式修改時,可以使用資料庫緩衝的方式提高效率