我有以下课程:
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查询以使其正常工作?
答案 0 :(得分:33)
您的查询应该按预期工作,只需稍微修改您使用distinct
的方式:
select count(distinct r.user) from Rating as r
where r.item = :item group by r.user
执行此查询的另一种方法是使用User
和join
:
select count(distinct u) from User as u
inner join u.ratings as r where r.item = :item
group by r.user
答案 1 :(得分: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));
答案 2 :(得分:0)
只需在交易中运行查询。
Transaction tx=session.beginTransaction;
//Run your query here
tx.commit();
问题出现是因为hibernate缓存。