2013-03-26 18 views
3

我是比較新的休眠,並在我的休眠類中添加一個「獨特」的限制時,我有一個問題。Hibernate的標準與Projections.groupProperty不能返回完整的Hibernate對象(拋出ClassCastException)

@Entity 
public class TaggedOffer { 
    private Long tagged_offers_id; 
    private String brand; 
    private Long cid; 
    private Date created_date; 
    //Getter and Setter and more fields 
} 

以前,我們正在創建一個Hibernate查詢如下:

public DetachedCriteria build(final TaggedOfferRequest request) { 

     DetachedCriteria criteria = DetachedCriteria.forClass(TaggedOffer.class); 

     criteria.add(Restrictions.eq("brand", request.getBrand())); 
     criteria.add(Restrictions.in("cid", request.getCids())); 

     // sort by date 
     criteria.addOrder(Property.forName("createdDate").desc()); 

     return criteria; 
} 

這將創建以下(工作)HQL查詢:

select 
     this_.tagged_offers_id as tagged1_2_3_, 
     this_.brand as brand2_3_, 
     this_.cid as cid2_3_, 
     this_.created_date as created6_2_3_ 
    from 
     site.tagged_offers this_ 
    where 
     this_.brand=? 
     and this_.country_code=? 
     and this_.cid in (
      ?, ? 
     ) 
    order by 
     this_.created_date desc limit ? 

來了棘手的部分。我們現在需要確保返回的結果在'cid'字段中有明顯區別。意思是,返回儘可能多的結果,提供每個記錄都有一個獨特的與它相關聯的cid。

我看着這個在SQL,它似乎是這樣做的最簡單的方法就是「由CID集團在查詢到有。在休眠的標準而言,這基本上是我一直在努力:

public DetachedCriteria build(final TaggedOfferRequest request) { 

     DetachedCriteria criteria = DetachedCriteria.forClass(TaggedOffer.class); 

     criteria.add(Restrictions.eq("brand", request.getBrand())); 
     criteria.add(Restrictions.in("cid", request.getCids())); 

     // sort by date 
     criteria.addOrder(Property.forName("createdDate").desc()); 

     // ** new ** distinct criteria 
     criteria.setProjection(Projections.groupProperty("cid")); 

     return criteria; 
} 

這幾乎創建了我要找的HQL,但後來拋出一個類轉換異常(因爲它只是選擇CID字段而不是整個對象)。

select 
    this_.cid as y0_ 
from 
    site.tagged_offers this_ 
where 
    this_.brand=? 
    and this_.country_code=? 
    and this_.cid in (
     ?, ? 
    ) 
    and tagtype1_.tag_type=? 
group by 
    this_.cid 
order by 
    this_.created_date desc limit ? 

和異常:

java.lang.ClassCastException: java.lang.Long cannot be cast to com.mycompany.site.taggedoffers.dao.model.TaggedOffer 

任何想法,我怎麼可以用投影做我想要什麼?

感謝您的幫助。

回答

1

爲您需要的所有列添加投影。

ProjectionList projectionList = Projections.projectionList(); 
    projectionList.add(Projections.groupProperty("cid")); 
    projectionList.add(Projections.property("tagged_offers_id")); 
    ... 
    criteria.setProjection(projectionList); 
+0

謝謝,這應該工作。 – JavaThunderFromDownunder 2013-03-28 20:49:33

+0

這不符合OP問題:類轉換異常仍然會觸發,因爲返回的對象實際上是Object []而不是'TaggedOffer'。 建議的答案可以用作一個「髒」的解決方法,它確實會帶回所有'TaggedOffer'的值。 我仍然感興趣的是一個解決方案,在投影之後帶回原始bean類型而不是Object表:... / – Attila 2016-12-20 03:07:20