2

I am using QueryDSL with Spring boot to retrieve records from database. I am able to sort the records by specifying the column name ("applicantid") like below:

@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);
}

But I want to sort by a parameter and pass it to the sort field (which can be applicantid, applicantname, etc - column fields). How to do it? I am not able to find proper syntax:

@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);
}

Only one column sorting is fine. If you can suggest with multiple column sorting that's great too. Please help me out. I am stuck at sorting. Thank you.

1 Answer 1

3

You are setting by which attribute you want to sort in

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

Instead of setting on your own, ask the client to send with which parameter you want to sort. So, your request would be like this:

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

This is equivalent to Pageable(sort = applicantId, Order = SortOrder.DESC, value =25)

You can pass multiple sorting params as well.

If you explicitly want to control over sort param, you can do like this:

    @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);
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.