二級緩存

    hibernate的session提供了一級緩存,在同一個session中對同一個id的對象load兩次,并不會發(fā)送兩條sql給數(shù)據(jù)庫。但是session關(guān)閉的時候,一級緩存就失效了。

    二級緩存是SessionFactory級別的全局緩存,它底下可以使用不同的緩存類庫,比如ehcache、oscache等,需要使用緩存實現(xiàn)方案。

    詳細請看: hibernate二級緩存攻略

 3.1 基本設(shè)置

1. 如果需要特別設(shè)置ehcache的屬性,把一個ehcache.xml 定義文件拷貝到class-path.

2. jdbc.properties加上

hibernate.cache.use_query_cache=true
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider

3. applicationContext.xml的 <property name="hibernateProperties">下加上

<prop key="hibernate.cache.use_query_cache">$ {hibernate.cache.use_query_cache}</prop>
<prop key="hibernate.cache.provider_class">$ {hibernate.cache.provider_class}</prop>

3.2 Entity級二級緩存

   Entity二級緩存是把PO放進cache,緩存的key就是ID,value是POJO,不同于查詢的緩存。

   Entity二級緩存在BookDao.get(3),和book.getCategory()的情況下都能用到,把category這樣的小表完全cache到內(nèi)存挺不錯的。

在hbm文件中: 

<class name="Product" table="PRODUCT" dynamic-insert="true" dynamic-update="true">
<cache usage="nonstrict-read-write"/>
<id name="id" column="ID">
<generator class="native"/>
</id>

   如果你使用的二級緩存實現(xiàn)是ehcache的話,需要配置ehcache.xml ,否則就會使用ehcache默認的配置

<cache name="com.xxx.pojo.Foo" maxElementsInMemory="500" eternal="false" timeToLiveSeconds="7200" timeToIdleSeconds="3600" overflowToDisk="true" />

3.3 查詢緩存

   上面的二級緩存是針對單個對象的,如果要對查詢結(jié)果,則是用下面的語句

query.setCacheable(true);//激活查詢緩存
query.setCacheRegion("myCacheRegion");//指定要使用的cacheRegion,可選

   cacheRegion是可選的,可以對使用的緩存進行特殊設(shè)置, 在ehcahe.xml里要補上下面的一段。

<cache name="myCacheRegion" maxElementsInMemory="10" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="7200" overflowToDisk="true" />