[英]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.我正在构建一个将调用另一个 API 并返回结果的 API。 The API I am calling has a paging and sorting mechanism that requires adding the following query params to the URL:我调用的 API 具有分页和排序机制,需要将以下查询参数添加到 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:现在,我希望我的 API 使用 Spring Pageable 对象作为控制器方法中的参数,因此,根据 Spring Docs,传递给我的新 API 的 URL 将是:
?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.因此,为了将接收到的可分页对象映射到我需要传递给底层 API 的所需查询参数,我需要从可分页对象中检索分页和排序信息。 As for the pageSize
and pageNumber
it is pretty straight forward:至于pageSize
和pageNumber
,它非常简单:
pageable.getPageNumber()
pageable.getPageSize()
But how can I retrieve sortField and sortDirection?但是如何检索 sortField 和 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) pageable.getSort()
返回 Sort 对象,我无法从中找到检索所需内容的方法 - sortField 值(具有属性名称的字符串)和 sortDirection 值(asc 或 desc)
Thanks谢谢
Pageable::getSort
will give you a Sort
, and that is an Iterable
of Sort.Order
s. Pageable::getSort
会给你一个Sort
,这是一个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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.