在hibernate.cfg.xml 中添加緩存 t1oo 一對多 t2oo (t2ooSet)
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="hibernate.cache.use_query_cache">true</property>
<mapping resource="hbn/bean/T1oo.hbm.xml" />
<mapping resource="hbn/bean/T2oo.hbm.xml" />
<class-cache class="hbn.bean.T1oo" usage="read-only" />
<collection-cache collection="hbn.bean.T1oo.t2ooSet" usage="read-only" />
<class-cache class="hbn.bean.T2oo" usage="read-only" />
在src根目錄下 ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000" //最大緩存數目
eternal="false"<!-- 緩存是否持久 -->
timeToIdleSeconds="120" <!-- 當緩存閑置n秒后銷毀 -->
timeToLiveSeconds="120"<!-- 當緩存存活n秒后銷毀-->
overflowToDisk="true"<!-- 是否保存到磁盤,當系統當機時-->
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"/>
<cache
name="hbn.bean.T1oo"
maxElementsInMemory="450"
eternal="false"
timeToLiveSeconds="600"
overflowToDisk="true"/>
</ehcache>
測試:
public void testCa()throws Exception{
System.out.println( getT1ooAll() );
Thread.sleep(2*1000);
System.out.println( getT1ooAll() );
}
控制臺輸出
Hibernate: select t1oo0_.id as id, t1oo0_.name as name0_ from t1oo t1oo0_ limit ?
Hibernate: select t2ooset0_.aid as aid1_, t2ooset0_.id as id1_, t2ooset0_.id as id0_, t2ooset0_.version as version1_0_, t2ooset0_.avg as avg1_0_, t2ooset0_.aid as aid1_0_ from t2oo t2ooset0_ where t2ooset0_.aid=?
Hibernate: select t2ooset0_.aid as aid1_, t2ooset0_.id as id1_, t2ooset0_.id as id0_, t2ooset0_.version as version1_0_, t2ooset0_.avg as avg1_0_, t2ooset0_.aid as aid1_0_ from t2oo t2ooset0_ where t2ooset0_.aid=?
24 : 23 : 25 : 2
//在這緩存成功 沒向數據庫提交 sql語句
24 : 23 : 25 : 2