19

我有以下课程:

class User {
  hasMany = [ratings: Rating] 
} 

class Item {
 hasMany = [ratings: Rating]
}

class Rating {
 belongsTo = [user: User, item: Item]
}

我想计算对某个项目进行评分的不同用户。

以下不起作用:

select count(distinct(r.user)) from Rating as r
        where r.item=:item
        group by r.user

我必须如何修改 HQL 查询才能使其工作?

4

2 回答 2

43

您的查询应按预期工作,只需对您的使用方式稍作修改distinct

select count(distinct r.user) from Rating as r 
where r.item = :item group by r.user

执行此查询的另一种但更冗长的方法是使用Userand join

select count(distinct u) from User as u 
inner join u.ratings as r where r.item = :item
group by r.user
于 2013-09-13T18:14:11.623 回答
0

这是在 Hibernate Criteria 中的操作方法

Criteria crit = session.createCriteria(Rating.class)
.add(Restrictions.like("item", item)
.addOrder(Order.asc("user"))
.setProjection(
       Projections.distinct(Projections.projectionList()
                        .add(Projections.property("user"), "user")))
.setResultTransformer(Transformers.aliasToBean(Rating.class));
于 2013-09-13T17:08:34.157 回答