I have two entities Customer and Order in a one-to-many relation. For each customer I need to count the number of associated orders and sort the results by this number. In a native postgres query it looks like this:
select cust.id, count(order.id) from customers cust
left outer join orders order
on cust.id = order.customer_id
where .... conditions ...
group by cust.id
order by count desc;
But I must do this using CriteriaBuilder because this query is part of a larger piece of code that uses CriteriaBuilder to put in additional conditions. In Hibernate I would have probably used Projections, but I can't find anything similar in JPA.
Any help in composing the query using CriteraBuilder would be much appreciated.
Thank you in advance.
Supposing that the entity Customer has a
OneToMany
property like this:You can use the following query:
The above approach uses Metamodel. If you don't like it, you can replace
Customer_.orders
with"orders"
andCustomer_.id
with"id"
.If the
OneToMany
property is of another type, replaceCollectionJoin
with the collection of the proper type (ListJoin
,SetJoin
,MapJoin
).