2013-02-21 37 views
1

我无法使@FetchProfile与HQL一起工作。FetchProfiles是否支持HQL?

我用它(旧)原生Criteria和session.get()API成功使用它,但与HQL无关。

这是正常吗?

感谢 我的映射和FetchProfile定义

@FetchProfiles({ @FetchProfile(name = "countryCities", 
      fetchOverrides = { @FetchOverride(entity = Country.class, 
         association = "cities", mode = FetchMode.JOIN) }) }) 
    public class Country implements java.io.Serializable { 

     @Id 
     private long id; 
     @Version 
     private int version; 
     private String country; 
     @OneToMany(mappedBy = "country") 
     private Set<City> cities = new HashSet<City>(0); 
    } 

以下不工作:

@Override 
public List<Country> findAllFetchProfileCities() { 
    getSession().enableFetchProfile("countryCities"); 
    boolean enabled = getSession().isFetchProfileEnabled("countryCities"); 
    List<Country> list = getSession().createQuery("from Country").list(); 
    enabled = getSession().isFetchProfileEnabled("countryCities"); 
    return list; 
} 

以下几项工作确定:

@Override 
public Country findOneFetchProfileCities(Long _id) { 
    getSession().enableFetchProfile("countryCities"); 
    Country c = (Country) getSession().get(Country.class, _id); 
    return c; 
} 

@Override 
public List<Country> findAllCriteriaFetchProfileCities() { 
    getSession().enableFetchProfile("countryCities"); 
    return getSession().createCriteria(Country.class).list(); 
} 

回答

0

的休眠Fetch策略都可用在Criteria API中(标准。 setFetchMode())和HQL(“FETCH JOIN”)。

所以,当我们写hql时,我们不得不提到关键词“JOIN”它在查询中自我存在,我认为

有点老了,但请参考这个曾经

Hibernate hard facts

+3

如果我不得不在HQL中添加关键字“join”或“join fetch”,那么fetchProfile将不会有用。 FetchProfile应该改变抓取计划,所以我不必这样做。当我在Criteria和session.get()上测试它时,它工作正常。 – 2013-02-22 11:04:10

1

我一直在寻找一个解决这个问题为好,并发现了什么,我认为是一个可用的变通(不是说这是有效的或任何东西)

它包括两个步骤:

首先添加级联REFRESH的映射:

@FetchProfiles({ @FetchProfile(name = "countryCities", 
     fetchOverrides = { @FetchOverride(entity = Country.class, 
        association = "cities", mode = FetchMode.JOIN) }) }) 
public class Country implements java.io.Serializable { 

    @Id 
    private long id; 
    @Version 
    private int version; 
    private String country; 
    @OneToMany(mappedBy = "country", cascade = {CascadeType.REFRESH}) 
    private Set<City> cities = new HashSet<City>(0); 
} 

然后引入环刷新由列表检索到的对象:

@Override 
public List<Country> findAllFetchProfileCities() { 
    getSession().enableFetchProfile("countryCities"); 
    boolean enabled = getSession().isFetchProfileEnabled("countryCities"); 
    List<Country> list = getSession().createQuery("from Country").list(); 
    enabled = getSession().isFetchProfileEnabled("countryCities"); 

    for (Country c:list) { 
     getSession().refresh(c); 
    } 

    return list; 
} 

这是丑陋的,但它进一步相处得我有点。