繁体   English   中英

Spring Boot按参数或路径变量排序

[英]spring boot sort by parameter or pathvariable

我在Spring Boot上使用QueryDSL从数据库检索记录。 我可以通过指定列名(“ applicantid”)对记录进行排序,如下所示:

@GetMapping("/applicants")
@ResponseBody
public Iterable<Applicant> getAllApplicants(@QuerydslPredicate(root = Applicant.class) Predicate predicate, @PageableDefault(sort = { "applicantid"}, value = 25) Pageable pageable) {
return this.applicantService.getAllApplicants(predicate, pageable);
}

但是我想按参数排序,并将其传递到排序字段(可以是Applicatorid,ApplicantName等-列字段)。 怎么做? 我找不到正确的语法:

@GetMapping("/applicants/{sortBy}")
@ResponseBody
public Iterable<Applicant> getAllApplicants(@QuerydslPredicate(root = Applicant.class) Predicate predicate, @PathVariable(value = "sortBy") String sortBy
@PageableDefault(sort = sortBy, value = 25) Pageable pageable) {
return this.applicantService.getAllApplicants(predicate, pageable);
}

仅一列排序就可以了。 如果您可以建议使用多列排序,那也很好。 请帮帮我。 我无法进行排序。 谢谢。

您正在设置要排序的属性

@PageableDefault(sort = sortBy, value = 25) Pageable pageable) . . .

而不是自行设置,而是要求客户端发送要排序的参数。 因此,您的请求将如下所示:

http://localhost:8080/applicants?sort=applicantId&applicantId.dir=desc&size=25

这等效于Pageable(sort = applicantId, Order = SortOrder.DESC, value =25)

您还可以传递多个排序参数。

如果您明确希望控制排序参数,则可以执行以下操作:

    @GetMapping("/applicants/{sortBy}")
    @ResponseBody
    public Iterable<Applicant> getAllApplicants(@QuerydslPredicate(root = Applicant.class) Predicate predicate,
                                                @PathVariable(value = "sortBy") String sortBy,
                                                Pageable pageable) {
        Sort sort = pageable.getSort();
        if (sort != null) {
            sort = new Sort(sortBy, "other params");
        }
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);

        return this.applicantService.getAllApplicants(predicate, pageable);
    }

暂无
暂无

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

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