我有一个数据模型,其中一个帐户可以有多个用户:
class Account {
Long id;
}
class User {
Long id;
@ManyToOne
Account account;
}
我想做以下查询,显示每个帐户的用户数量:
select Account.id, NumUsers.num from Account,
(select Account.id as account_id, count(User.id) as num
from User join Account on User.account_id=Account.id
group by Account.id) as NumUsers
where Account.id=NumUsers.account_id;
我知道我可以将这个特定查询重写为:
select Account.id, count(User.id) from Account join
User on User.account_id=Account.id group by Account.id
但我计划为需要多个分组依据的报表创建更复杂的查询。我读过here关于多重分组的正确方法。
如何使用 JPA2 Criteria API 创建查询?
最佳答案
您不能在 JPA 2 Criteria API 的 FROM 子句中使用子查询。它确实具有与 JPQL 相同的限制。在 JPA 2 规范中,关于 JPQL 中的子查询有以下规定:
Subqueries may be used in the WHERE or HAVING clause.
Criteria API 中关于子查询的说法得出了相同的结论:
Both correlated and non-correlated subqueries can be used in restriction predicates. A subquery is constructed through the creation and modification of a Subquery object.
A Subquery instance can be passed as an argument to the all, any, or some methods of the CriteriaBuilder interface for use in conditional expressions.
A Subquery instance can be passed to the CriteriaBuilder exists method to create a conditional predicate.
关于jpa-2.0 - JPA 2 Criteria 中 From 子句中的子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11573591/