简体   繁体   English

如何使用我的规格书中的CriteriaQuery订购列表?

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

I'm trying to order the lists returned by my JpaRepository. 我正在尝试订购JpaRepository返回的列表。 I'm using Specification classes rather than the @Query annotation, and according to this question , I'm supposed to use a CriteriaQuery object. 我使用的是Specification类而不是@Query注释,根据这个问题 ,我应该使用CriteriaQuery对象。

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 . 如您所见,这里有两个实体类MessageEntityDemandeEntity ,其中MessageEntity具有引用DemandeEntity的属性。 So in this specification, I'm getting a list of MessageEntity that have the specified DemandeEntity 's ID. 因此,在本规范中,我将获得具有指定的DemandeEntity的ID的MessageEntity列表。

Now I would like to do the equivalent of an ORDER BY Message.ID . 现在,我想做一个相当于ORDER BY Message.ID To do so, I tried using the CriteriaQuery object in my predicate (variable query ) : 为此,我尝试在谓词(变量query )中使用CriteriaQuery对象:

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() . 但这不起作用,无论我使用criteriaBuilder.desc()还是criteriaBuilder.asc() ,它都仍以相同的顺序返回列表。

I'm guessing I'm doing something wrong, how am I supposed to use that CriteriaQuery object ? 我猜我做错了什么,我应该如何使用那个CriteriaQuery对象?

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 : 我发现规范类没有解决方案,所以我决定使用Sort类对列表进行排序:

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: JpaRepository的findAll接受Sort对象作为参数以及Specification:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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