Java Hibernate HQL Count Distinct 不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18791580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hibernate HQL Count Distinct not working?
提问by confile
I have the following classes:
我有以下课程:
class User {
hasMany = [ratings: Rating]
}
class Item {
hasMany = [ratings: Rating]
}
class Rating {
belongsTo = [user: User, item: Item]
}
I want to count the distinct users that rated on an item.
我想计算对某个项目进行评分的不同用户。
The following does not work:
以下不起作用:
select count(distinct(r.user)) from Rating as r
where r.item=:item
group by r.user
How do I have to modify the HQL query to make it work?
我必须如何修改 HQL 查询才能使其工作?
采纳答案by dmahapatro
Your query should work as expected with a minor modification to the way you use distinct
:
您的查询应该按预期工作,只需对您的使用方式稍作修改distinct
:
select count(distinct r.user) from Rating as r
where r.item = :item group by r.user
An other, but more lengthy way, of doing this query is by using User
and join
:
执行此查询的另一种但更冗长的方法是使用User
and join
:
select count(distinct u) from User as u
inner join u.ratings as r where r.item = :item
group by r.user
回答by aksappy
This is how to do in Hibernate Criteria
这是在 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));
回答by coding_idiot
Simply run the query within a transaction.
只需在事务中运行查询。
Transaction tx=session.beginTransaction;
//Run your query here
tx.commit();
The problem arises because of hibernate caching.
问题是由于休眠缓存而出现的。