JPA Criteria-API:使用子查询进行连接

12

这个查询用于检索一对多关系中的最后记录(参见 SQL join: selecting the last records in a one-to-many relationship)。

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;

我的问题: 如何使用JPA Criteria API 建立包含子查询的连接?这是否可能?如果不行,那么用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();

解决这个问题作为参考和练习可能会很有趣,尽管在三年后你可能不再需要它。请问你能给出表格的结构吗? - Kalle Richter
1个回答

1

使用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)
;

使用 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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接