Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

jpa 2.0 - Subquery in From claus in JPA2 Criteria

I have a data model where an account can have multiple users:

class Account {
    Long id;
}
class User {
    Long id;
    @ManyToOne
    Account account;
}

I'd like to do the following query which displays the number of users of each 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;

I know I can re-write this specific query as:

select Account.id, count(User.id) from Account join 
       User on User.account_id=Account.id group by Account.id

But I plan to create more complicated queries for reports that require more than one group by. I read here about the correct approach to multiple group by.

How can I create my query using JPA2 Criteria API?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot use subquery in FROM clause with JPA 2 Criteria API. It does have same limitations as JPQL does. In JPA 2 specification following is said about subqueries in JPQL:

Subqueries may be used in the WHERE or HAVING clause.

And what is said about subqueries in Criteria API leads to same conclusion:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...