2011-02-23 74 views
0

我有一個實體直接映射到UI,它有一些查找表,其中數據根本不會改變。在我的控制器中,我在查找表上使用findAll來獲取所有值並將其設置爲模型。JPA Hibernate與onetoone關聯的EHCACHE問題 - QueryCache

主要實體

@Entity 
public class MainEntity implements Serializable { 
    @OneToOne(cascade = CascadeType.ALL, optional=true) 
    @JoinColumn(name="lookup_entity_key") 
    private LookupEntity luentity; 
} 

查找實體:

@Entity 
@Table(name="lookup_entity") 
@Cacheable 
public class LookupEntity implements Serializable { 

} 

我已啓用persistence.xml中的二級緩存。下面

<property name="hibernate.cache.use_second_level_cache" value="true" /> 
<property name="hibernate.cache.use_query_cache" value="true" /> 
<property name="hibernate.cache.region.factory_class" value="net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory" /> 
<property name="javax.persistence.sharedCache.mode" value="ENABLE_SELECTIVE" /> 

的FindAll查詢緩存配置:

entityManager.createQuery("from " + this.entityClass.getName()) 
       .setHint("org.hibernate.cacheable", true) 
       .getResultList(); 

當有史以來請求從UI來它試圖調用LookupEntity對象的findAll方法。出於某種原因,第一個請求正確調用findAll sql,但隨後的請求正在爲LookupEntity中存在的所有行調用findById SQL。這是一種預期的行爲,或者是我的配置有問題。

請幫忙!!!

謝謝!

回答

1

它是預期的行爲:查詢緩存將返回實體的ID,Hibernate將加載實體本身。因此,由緩存查詢查詢的實體應位於第二級實體緩存中,以便操作有益。

這是the documentation

查詢緩存不會緩存在 緩存的實際實體的 狀態;它只緩存標識符 值和值類型的結果。對於 這個reaso,查詢緩存 始終在與預計將緩存爲 查詢結果緩存(就像使用 集緩存)的一部分,這些實體 的 二級緩存一起使用。

+0

感謝JB Nizet的迴應。我已經通過一些論壇,並注意到我們可以使用「複合元素」爲兒童實體來解決這個問題。它是否正確?我找不到相應的JPA註釋。 – Vmad 2011-02-23 21:11:14