我对 Hibernate 比较陌生,在我的 hibernate 类上添加“不同”限制时遇到问题。
@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
}
以前,我们正在创建一个休眠查询,如下所示:
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
在查询中添加一个。就休眠标准而言,这基本上是我一直在尝试的:
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 ?
还有一个例外:
java.lang.ClassCastException: java.lang.Long cannot be cast to com.mycompany.site.taggedoffers.dao.model.TaggedOffer
知道如何使用投影来做我想做的事吗?
谢谢你的帮助。