问题
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