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

NattyRoots :

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 ?

NattyRoots :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=162919&siteId=1