具有内部对象的查询不会在Hibernate

时间:2017-09-10 11:42:24

标签: java hibernate caching

我发现,这是一个非常简单的查询,比如

        Session s = sessionFactory.getCurrentSession();
        List<Mod> list = s.createQuery("from Mod m where m.modNameShort=:modName")
                .setParameter("modName", modName)
                .setCacheable(true)
                .list();

缓存得很好。

但缓存不适用于一对多选择,如下所示:

List<ModVersion> list = s.createQuery("select m.modsVersionses from Mod m")
                .setCacheable(true)
                .list();

它仍会在第二次和下次呼叫时向DB发出请求。

我有

        props.setProperty("hibernate.cache.provider_class", "org.hibernate.cache.EhCacheProvider");
        props.setProperty("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
        props.setProperty("hibernate.cache.use_second_level_cache", "true");
        props.setProperty("hibernate.cache.use_query_cache", "true");
        factoryBean.setHibernateProperties(props);

,Mod对象看起来像

@Entity
@Table(name = "mods", catalog = "artfunpw")
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)
public class Mod implements java.io.Serializable {
***
 @OneToMany(fetch = FetchType.LAZY, mappedBy = "mods") 
    @OrderBy("ReleaseDate desc")
    public Set<ModVersion> getModsVersionses() {
        return this.modsVersionses;
    }
***

ModVersion对象看起来像

@Entity
@Table(name = "mods_versions", catalog = "artfunpw", uniqueConstraints = @UniqueConstraint(columnNames = "VersionNumber"))
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)
public class ModVersion implements java.io.Serializable {

如何为这种一对多查询启用缓存?

谢谢!

1 个答案:

答案 0 :(得分:0)

可能,我的问题是重复的。

我在Using hibernate 2nd level cache or query cache for lazy fetch querieshttp://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#performance-cache-mapping

找到了答案

我应该添加@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "mods", cascade = {CascadeType.ALL})  
    @OrderBy("ReleaseDate desc")
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) 
    public Set<ModVersion> getModsVersionses() {
        return this.modsVersionses;
    }