Support for sorting by nested fields when using distinct in SQL databases

As the documentation states:

Because of limitations of SQL databases, when the distinct flag is set to true, you cannot sort by nested properties.

This limitation can be overcome by using a tuple query in JPA, and adding the entity as first element of the tuple and the sort fields as other elements of the tuple.

Example:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<T> root = cq.from(entityClass);
cq.distinct(true);
cq.orderBy(cb.asc(sortField));
cq.multiselect(root, sortField);
List<T> results = entityManager.createQuery(cq).getResultList().stream()
        .map(t -> t.get(0, entityClass))
        .toList();

Tasks:

  • implement failing test
  • refactor the code to apply the change to make the test pass
  • update documentation