use*_*611 9 criteria-api jpa-2.0
此查询用于以一对多关系检索最后的记录(请参阅SQL连接:选择一对多关系中 的最后记录)
SELECT p.*
FROM customer c
INNER JOIN (
SELECT customer_id, MAX(date) MaxDate
FROM purchase
GROUP BY customer_id
) MaxDates ON c.id = MaxDates.customer_id
INNER JOIN purchase p ON MaxDates.customer_id = p.customer_id
AND MaxDates.MaxDate = p.date;
Run Code Online (Sandbox Code Playgroud)
我的问题:如何使用jpa criteria-api的subselect构建此连接?可能吗?如果没有,可以使用jpql吗?
我的代码到目前为止:
final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
final CriteriaQuery<Purchase> query = cb.createQuery(Purchase.class);
final Root<CustomerEntity> root = query.from(Customer.class);
// here should come the join with the sub-select
final Path<Purchase> path = root.join(Customer_.purchases);
query.select(path);
final TypedQuery<Purchase> typedQuery = entityManager.createQuery(query);
return typedQuery.getResultList();
Run Code Online (Sandbox Code Playgroud)
在JPA2.0中无法实现这样的查询,但是我们可以通过重构查询来解决
SELECT p.*
FROM customer c
/* This part gets the maximum date of a customer purchase
We will replace it with a subquery in the where
INNER JOIN (
SELECT customer_id, MAX(date) MaxDate
FROM purchase
GROUP BY customer_id
) MaxDates ON c.id = MaxDates.customer_id */
/* This part crosses the maximum date of a customer with the purchase itself to obtain the information
INNER JOIN purchase p ON MaxDates.customer_id = p.customer_id
AND MaxDates.MaxDate = p.date*/
-- We make the crossing with the purchase (there will be N tickets per customer, with N being the number of purchases)
INNER JOIN purchase p on p.customer_id = c.id
-- In the where clause we add a condition so that these N entries become that of the maximum date
WHERE p.date = (
SELECT MAX(p2.date)
FROM purchase p2
WHERE p2.customer_id = c.id)
;
Run Code Online (Sandbox Code Playgroud)
criteria-api 的实现是这样的
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Purchase> query = cb.createQuery(Purchase.class);
Root<Customer> root = query.from(Customer.class);
Join<Customer,Purchase> join = root.join(root.get("purchases"),JoinType.INNER);
Subquery<Date> sqMaxdate = cq.subquery();
Root<Purchase> sqRoot = sqMaxDate.from(Purchase.class);
Join<Purchase,Consumer> sqJoin = sqRoot.join(sqRoot.get("customer"),JoinType.INNER)
sqMaxDate.select(cb.max(sqRoot.get("date")));
sqMaxDate.where(cb.equal(sqJoin.get("id"),root.get("id")));
query.where(cb.equal(join.get("date"),sqMaxDate.getSelection()));
query.select(join);
TypedQuery<Purchase> typedQuery = entityManager.createQuery(query);
return typedQuery.getResultList();
Run Code Online (Sandbox Code Playgroud)