0

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?

membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • there is a property to put in application.properties : spring.jpa.properties.hibernate.order_by.default_null_ordering=last/first. but may be you want to apply it dynamically? – zpavel Sep 10 '19 at 14:54
  • What's the default value for this? But indeed I'd like to apply this dynamically per property (some properties I want to sort nulls_last by default, and some nulls_first). – membersound Sep 10 '19 at 14:58
  • 1
    default is none. i will try to provide you a solution. – zpavel Sep 10 '19 at 15:05

2 Answers2

3

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));
}
zpavel
  • 951
  • 5
  • 11
-1

Try to do something like :

pageable.getSort().and(Sort.by(new Sort.Order(Sort.Direction.DESC, "age", Sort.NullHandling.NULLS_LAST)));
Saad
  • 1,047
  • 2
  • 19
  • 32