Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I retrieve sort property and direction from a Spring Data Pageable?

I am building an API that will call another API and return results. The API I am calling has a paging and sorting mechanism that requires adding the following query params to the URL:

?pageNumber=1&pageSize=20&sortField=id&sortDirection=asc

Now, I would like my API to use a Spring Pageable object as a parameter in the controller method, so, according to Spring Docs the URL passed to my new API will be:

?page=1&size=20&sort=id,asc

Therefore, in order to map the received pageable object to the required query params that I need to pass to the uinderlying API I need to retrieve the paging and sorting information from the Pageable object. As for the pageSize and pageNumber it is pretty straight forward:

pageable.getPageNumber()
pageable.getPageSize()

But how can I retrieve sortField and sortDirection?

pageable.getSort() returns the Sort object, from which I could not find a way to retrieve what i need - the sortField value (string with property name) and sortDirection value (asc or desc)

Thanks

like image 722
furry12 Avatar asked Jan 24 '20 13:01

furry12


1 Answers

Pageable::getSort will give you a Sort, and that is an Iterable of Sort.Orders. You need to iterate over each of these. They contain the properties you're looking for.

Sort sort = Sort.by(Sort.Direction.ASC, "abc");

for (Sort.Order order : sort)
{
    System.out.println("Property: " + order.getProperty());
    System.out.println("Direction: " + order.getDirection());
}

Prints

Property: abc
Direction: ASC
like image 55
Michael Avatar answered Oct 27 '22 08:10

Michael