我有一个数据模型,其中一个帐户可以有多个用户:
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
但我计划为需要多个分组依据的报告创建更复杂的查询。我在这里读到了关于多个分组的正确方法。
如何使用 JPA2 Criteria API 创建查询?