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
Pageable::getSort
will give you a Sort
, and that is an Iterable
of Sort.Order
s. 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With