This query is used to retrieve the latest records in a one-to-many relationship (see SQL Join: Selecting the Latest 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;
My question is: How can I build this connection with a subquery using jpa criteria-api? Is it possible? If not, maybe using jpql?
My code is:
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();
source share