淺析Hibernate使用EhCache
在Hibernate使用EhCache
EhCache是一個純JAVA程序,可以在Hibernate中作為一個插件引入。在Hibernate使用EhCache需要在Hibernate的配置文件中設(shè)置如下:
- <propery name="hibernate.cache.provider_class">
- org.hibernate.cache.EhCacheProvider
- </property>
- <ehcache>
- <diskStore path="c:\\cache"/>
- //設(shè)置cache.data文件存放位置
- <defaultCache
- maxElementsInMemory="10000"
- //緩存中允許創(chuàng)建的最大對象數(shù)
- eternal="false"
- //緩存中對象是否為永久的
- timeToIdleSeconds="120"
- //緩存數(shù)據(jù)鈍化時間(即對象在它過期前的空閑時間)
- timeToLiveSeconds="120"
- //緩存數(shù)據(jù)生存時間(即對象在它過期前的生存時間)
- overflowToDisk="true"
- />
- <cache name="Student"
- //用戶自定義的Cache配置
- maxElementsInMemory="10000"
- eternal="false"
- timeToIdleSeconds="300"
- timeToLiveSeconds="600"
- overflowToDisk="true"
- />
- </ehcache>
此外我們還需要在持久化類的映射文件中進行配置。例如,Group(班級)和Student(學(xué)生)是一對多的關(guān)系,它們對應(yīng)的數(shù)據(jù)表分別是t_group和t_student.現(xiàn)在要把Student類的數(shù)據(jù)進行二級緩存,這需要在二個映射文件中都對二級緩存進行配置。
在Group.hbm.xml中如下,在其<set></set>中添加
<cache usage="read-write"/><!——集合中的數(shù)據(jù)被緩存——>上述文件雖然在<set>標記中設(shè)置了& lt;cache usage="read-write"/>,但Hibernate只是把Group相關(guān)的Student的主鍵ID加入到緩存中,如果希望把整個 Student的散裝屬性都加入到二級緩存中,還需要在Student.hbm.xml文件的<class>標記中添加<cache>子標記。如下:
- <class name="Student" table="t_student">
- <cache usage="read-write" /><!--cache標記需跟在class標記后-->
- </class>
【編輯推薦】