假设实体 Customer 具有OneToMany
如下属性:
@OneToMany(mappedBy = "customerId")
private Collection<Order> orders;
您可以使用以下查询:
EntityManager em; // to be built or injected
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<Customer> customer = cq.from(Customer.class);
CollectionJoin<Customer, Order> orders = customer.join(Customer_.orders, JoinType.LEFT);
cq.select(cb.tuple(customer, cb.count(orders)));
cq.where(... add some predicates here ...);
cq.groupBy(customer.get(Customer_.id));
cq.orderBy(cb.desc(cb.count(orders)));
List<Tuple> result = em.createQuery(cq).getResultList();
for (Tuple t : result) {
Customer c = (Customer) t.get(0);
Long cnt = (Long) t.get(1);
System.out.println("Customer " + c.getName() + " has " + cnt + " orders");
}
上述方法使用Metamodel。如果你不喜欢它,你可以Customer_.orders
用"orders"
和Customer_.id
替换"id"
。
如果OneToMany
属性是另一种类型,则替换CollectionJoin
为正确类型的集合(ListJoin
, SetJoin
, MapJoin
)。