简体   繁体   中英

How do I configure a lazy-loaded collection to utilize my Hibernate second level cache?

I'm using Java 7 with Hibernate 5.1.5.Final. I'm trying to figure out how to cache a query that occurs as a result of loading a lazy collection. Here is my entity ...

@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;
    }

My second level cache is configured (through Spring) like so ...

<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>

Although the entity itself is marked with the "@Cache" annotation, calling "getChildren" results in a query. How do I configure my entity (or application) so that I take advantage of the cache?

Found that the @Cache annotation was the way to do this ...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM