1. 程式人生 > >MyBatis整合第三方緩存

MyBatis整合第三方緩存

encoding size 緩存技術 hibernate round 保存 磁盤 tca myba

MyBatis緩存做的並不專業,用的是map,但是它給了我們一個接口Cache,我們通過實現這個接口,可以自定義緩存。本例子用的為ehcache ,Hibernate用的也是ehcache緩存技術。
首先我們從官網上下載ehcache的jar包,還需要兩個相關的jar。在MyBatis的基礎上需要導入的jar包為 ehcache-core-2.6.8.jar slf4j-api-1.6.1.jar 和 slf4j-log4j12-1.6.2.jar (請忽略版本號)。
接下來我們需要寫一個Cache的實現。但是MyBatis已經幫我們做好了,在MyBatis官網上有MyBatis和各種項目的整合。我們找到和ehcache的整合,如圖:技術分享

點進去之後:查看文檔

技術分享

根據提示下載mybatis和ehcache整合所需要的jar包。如 mybatis-ehcache-1.0.3.jar 導入項目中。

接下來就是如何使用了,我們只需要在mapper.xml中指定一個Cache標簽。

<mapper namespace="org.acme.FooMapper">
  <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
  ...
</mapper>
然後還需要在類路徑下放一個ehcache.xml文件。文件內容如下:

<?xml version="1.0" encoding="UTF-8"?>


<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<!-- 磁盤保存路徑 -->
<diskStore path="D:\44\ehcache" />

<defaultCache
maxElementsInMemory="1000"
maxElementsOnDisk="10000000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="120"

timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>

第三方緩存整合總的來說 就三步:

  1、導入第三方jar包

  2、導入與第三方緩存整合的適配包,官方有。

  3、mapper.xml 中使用自定義緩存   

<mapper namespace="org.acme.FooMapper">
  <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
  ...
</mapper>
其他mapper.xml中如果也想使用 只需要引用已經使用的mapper.xml 的命名空間即可
如:
<mapper namespace="org.acme.AooMapper">
  <cache-ref namespace="org.acme.FooMapper" />
..
</mapper>
如果有什麽問題歡迎討論。大家一起進步!

MyBatis整合第三方緩存