2

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 ?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Natty
  • 497
  • 1
  • 11
  • 23

2 Answers2

0

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();
Artiow
  • 351
  • 1
  • 9
  • Unfortunately it does not work :( I've tried using `asc()` and `desc()` once again and I have the same result @Artiow – Natty Jun 25 '19 at 13:15
0

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());
Natty
  • 497
  • 1
  • 11
  • 23