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

时间:2018-07-12 02:51:17

标签: java rest sorting spring-boot

我将QueryDSL与Spring boot结合使用,以从数据库中检索记录。我可以通过指定列名(“ 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);
}

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

1 个答案:

答案 0 :(得分:0)

您正在设置要在其中排序的属性

@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);
    }
相关问题