我是 Hibernate 的新手,在我的 hibernate 类上添加“distinct”限制时遇到了问题。
@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;
}
这将创建以下(有效的)SQL 查询:
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 中对此进行了研究,看起来最简单的方法就是在查询中使用 group by cid
。就 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());
// ** new ** distinct criteria
criteria.setProjection(Projections.groupProperty("cid"));
return criteria;
}
这几乎创建了我正在寻找的 SQL,但它后来抛出了一个类转换异常(因为它只是选择了 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 ?
异常(exception)情况:
java.lang.ClassCastException: java.lang.Long cannot be cast to com.mycompany.site.taggedoffers.dao.model.TaggedOffer
知道如何使用投影来做我想做的事吗?
感谢您的帮助。
最佳答案
为您需要的所有列添加投影。
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.groupProperty("cid"));
projectionList.add(Projections.property("tagged_offers_id"));
...
criteria.setProjection(projectionList);
关于java - Hibernate Criteria with Projections.groupProperty 无法返回完整的 hibernate 对象 (ClassCastException),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15644602/