How can I order a list using the CriteriaQuery in my Specifications?

Viewed 273

I'm trying to order the lists returned by my JpaRepository. I'm using Specification classes rather than the @Query annotation, and according to this question, I'm supposed to use a CriteriaQuery object.

My specification is currently as follow :

public class MessageSpecification {

    public static Specification<MessageEntity> hasDemandeId(Long demandeId) {
        return (root, query, criteriaBuilder) -> {
            // TODO : order the list
            return criteriaBuilder.equal(root.join(MessageEntity_.demande).get(DemandeEntity_.idTechnique), demandeId);
        };
    }
}

As you can see, I have here two entity classes MessageEntity and DemandeEntity where MessageEntity has a property referencing a DemandeEntity. So in this specification, I'm getting a list of MessageEntity that have the specified DemandeEntity's ID.

Now I would like to do the equivalent of an ORDER BY Message.ID. To do so, I tried using the CriteriaQuery object in my predicate (variable query) :

return (root, query, criteriaBuilder) -> {
    query.orderBy(criteriaBuilder.asc(root.get(MessageEntity_.idTechnique)));
    return criteriaBuilder.equal(root.join(MessageEntity_.demande).get(DemandeEntity_.idTechnique), demandeId);
};

But it does not work, it's still returning the list in the same order whether I use criteriaBuilder.desc() or criteriaBuilder.asc().

I'm guessing I'm doing something wrong, how am I supposed to use that CriteriaQuery object ?

2 Answers

Try this:

return query.where(criteriaBuilder.equal(root.join(MessageEntity_.demande).get(DemandeEntity_.idTechnique), demandeId))
            .orderBy(cb.asc(root.get(MessageEntity_.idTechnique)))
            .distinct(true)
            .getRestriction();

I found no solution with the Specification class so I decided to use the Sort class to order my list :

public Sort sortByIdTechnique(){
    return new Sort(Sort.Direction.ASC, "idTechnique");
}

JpaRepository's findAll accept a Sort object as a parameter as well as a Specification:

List<MessageEntity> messages = repository.findAll(MessageSpecification.hasDemandeId(idDemande), sortByIdTechnique());
Related