How to use Pageable as get-query parameter in spring-data-rest?

故事扮演 提交于 2021-01-29 13:21:31

问题


I have a simple query controller that takes query parameters (as Person dto) and a Pageable:

@RestController
public class PersonController {
   @GetMapping("/persons")
   public Object search(org.springframework.data.domain.Pageable pageable, Person form) {
       repository.findAll(form, pageable);
   }
}

The pageable can take both sort and page parameters as follows:

http://localhost:8080/persons?sort=age,desc&page=5

Problem: for the sort, I want to add order hints like NULLS_LAST or NULLS_FIRST.

Question: how can I achieve this using query params too?


回答1:


You can modify Pageable object like this (method to put in your controller for example). This is an example with one sort field, but you can loop on all fields and modify nullsLast/nullsFirst in the same way. Please try :

private Pageable customSort(Pageable pageable) {
    Sort sort = pageable.getSort();
    Order order = sort.iterator().next();
    List<Order> orders = new ArrayList<>();
    // nullsFirst or nullsLast
    orders.add(new Order(order.getDirection(),order.getProperty()).nullsFirst());
    return PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), Sort.by(orders));
}



回答2:


Try to do something like :

pageable.getSort().and(Sort.by(new Sort.Order(Sort.Direction.DESC, "age", Sort.NullHandling.NULLS_LAST)));


来源:https://stackoverflow.com/questions/57873119/how-to-use-pageable-as-get-query-parameter-in-spring-data-rest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!