JPA CriteriaBuilder

JPA CriteriaBuilder,第1张

JPA CriteriaBuilder

假设实体客户具有如下

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
)。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4923378.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存