假设实体客户具有如下
OneToMany属性:
@oneToMany(mappedBy = "customerId")private Collection<Order> orders;
您可以使用以下查询:
EntityManager em; // to be built or injectedCriteriaBuilder 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)。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)