20.2.1. 緩存映射(Cache mappings)
類或者集合映射的“<cache>元素”可以有下列形式:
<cache
usage="transactional|read-write|nonstrict-read-write|read-only" (1)
/>
(1) |
usage說明了緩存的策略: transactional、 read-write、 nonstrict-read-write或 read-only。 |
另外(首選?), 你可以在hibernate.cfg.xml中指定<class-cache>和 <collection-cache> 元素。
這里的usage 屬性指明了緩存并發策略(cache concurrency strategy)。
20.2.2. 策略:只讀緩存(Strategy: read only)
如果你的應用程序只需讀取一個持久化類的實例,而無需對其修改, 那么就可以對其進行只讀 緩存。這是最簡單,也是實用性最好的方法。甚至在集群中,它也能完美地運作。
<class name="eg.Immutable" mutable="false">
<cache usage="read-only"/>
....
</class>
20.2.3. 策略:讀/寫緩存(Strategy: read/write)
如果應用程序需要更新數據,那么使用讀/寫緩存 比較合適。 如果應用程序要求“序列化事務”的隔離級別(serializable transaction isolation level),那么就決不能使用這種緩存策略。 如果在JTA環境中使用緩存,你必須指定hibernate.transaction.manager_lookup_class屬性的值, 通過它,Hibernate才能知道該應用程序中JTA的TransactionManager的具體策略。 在其它環境中,你必須保證在Session.close()、或Session.disconnect()調用前, 整個事務已經結束。 如果你想在集群環境中使用此策略,你必須保證底層的緩存實現支持鎖定(locking)。Hibernate內置的緩存策略并不支持鎖定功能。
<class name="eg.Cat" .... >
<cache usage="read-write"/>
....
<set name="kittens" ... >
<cache usage="read-write"/>
....
</set>
</class>