2017-08-16 53 views
1

我使用Java 7與Hibernate 5.1.5.Final。我試圖找出如何緩存由於加載懶惰集合而發生的查詢。這是我的實體...如何配置延遲加載的集合以利用我的Hibernate二級緩存?

@Entity 
@Table(name = "my_item") 
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) 
public class MyItem implements Serializable, Comparable<MyItem> 

... 

    @OneToMany(fetch = FetchType.LAZY) 
    @JoinColumn(name = "PARENT_ID") 
    @OrderBy("orderNumber") 
    private Set<MyItem> children = new TreeSet<MyItem>(); 

... 
    public Set<MyItem> getChildren() { 
     return children; 
    } 

我的二級緩存配置(通過春季)是這樣的...

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> 
    <property name="packagesToScan" value="org.collegeboard.springboard" /> 
    <property name="jpaVendorAdapter"> 
     <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/> 
    </property> 
    <property name="dataSource" ref="dataSource"/> 
    <property name="jpaPropertyMap" ref="jpaPropertyMap" /> 
</bean> 

<util:map id="jpaPropertyMap"> 
    <entry key="hibernate.show_sql" value="false" /> 
    <entry key="hibernate.hbm2ddl.auto" value="validate"/> 
    <entry key="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/> 
    <entry key="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup" /> 
    <entry key="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory"/> 
    <entry key="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider"/> 
    <entry key="hibernate.cache.use_second_level_cache" value="true" /> 
    <entry key="hibernate.cache.use_query_cache" value="${enable.hibernate.query.cache}" /> 
    <entry key="hibernate.generate_statistics" value="false" /> 
    <entry key="hibernate.event.merge.entity_copy_observer" value="allow" /> 
    <entry key="hibernate.enable_lazy_load_no_trans" value="true" /> 
</util:map> 

雖然實體本身標有「@Cache」的註釋,調用「getChildren」會導致查詢。如何配置我的實體(或應用程序),以便利用緩存?

回答

0

發現這個@Cache註釋是做到這一點的方式......

@OneToMany(fetch = FetchType.LAZY) 
@JoinColumn(name = "PARENT_ID") 
@OrderBy("orderNumber") 
@Cache(usage=CacheConcurrencyStrategy.TRANSACTIONAL) 
private Set<MyItem> children = new TreeSet<MyItem>();