简体   繁体   中英

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

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM