I'm trying to find an elegant way of sorting the results of a JPA criteria query using the properties of the first of a collection of child object rather than with the object itself. E.g:
@Entity
class Parent {
protected Set<Child> children;
}
@Entity
class Child {
protected Date timestamp;
}
A parent can have several children each with a different timestamp.
I want to be able to add to an existing JPA CriteriaQuery/TypedQuery so that sorts the list of Parent objects by MAX(child.timestamp), so the parent with the latest child timestamp appears first.
My general-purpose criteria builder implementation is like this:
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(daoClass);
Root<T> queryRoot = criteriaQuery.from(daoClass);
// add wheres
Predicate filters = createPredicate(criteriaQuery, queryRoot, criteriaBuilder);
// filters = criteriaBuilder.and( /* lots of Predicate filter objects */ );
criteriaQuery.where(filters);
// add sorts
criteriaQuery.orderBy(createOrders(queryRoot, criteriaBuilder));
// <-- Ideally somewhere here add the new ordering
TypedQuery<T> typedQuery = em.createQuery(criteriaQuery);
Hopefully there is a solution that won't break it too much..
Thanks for any help.
EDIT: The Parent data that is gathered in the query is paged, so I can't sort the results of the query. It needs to be part of the JPA query I construct.