0

(I'm using Micronaut) I have a list of students and I want to sort it by name. I am using Pageable and sort as query parameters

http://localhost:8080/admin/students?page=0&size=10&sort=name,asc&status=graduated

and I get this result:

  • Samantha
  • Tim
  • antonio
  • david
  • sofia

Instead of:

  • antonio
  • david
  • Samantha
  • sofia
  • Tim

I have tried the options using Sort.Order, based on

PagingAndSortingRepository how to sort case insensitive?

Spring Data JPA: case insensitive orderBy

I removed the sorting from my url and tried if Sort.Order works

Sort.Order order = new Sort.Order("name",Sort.Order.Direction.ASC, true);

http://localhost:8080/admin/students?page=0&size=10&status=graduated

but it didn't, it doesn't do any sorting neither

Steps:

  1. Repository, added Sort.Order

     @Repository
     public interface StudentRepository extends PageableRepository<Student, Long> {
    
        Page<Student> findByGraduatedIsNull(Student.Status status, @Nullable Pageable p, Sort.Order sort);
    
     }
    
  2. Service

     public Page<Student> getStudents(Student.Status status, Pageable pageable){
    
         Sort.Order order = new Sort.Order("name",Sort.Order.Direction.ASC, true);
         Page<Student> studentPage =
                         studentRepository.findByGraduatedIsNull(status, pageable, order);
         return studentPage.map(s -> studentTransform.toDto(s));
    
     }
    

What could be the problem?

Andronicus
  • 25,419
  • 17
  • 47
  • 88
marhg
  • 659
  • 1
  • 17
  • 30

1 Answers1

0

The Pageable interface supports sorting, so not sure why you would pass both a Pageable and Sort.Order parameter (I don't know if that is even supported). If no sort was defined on the URL, the getSort() on Pageable should return UNSORTED. So that may be taking precedent over the Sort.Order.

Why don't you check if a sort was passed in on the request, and if not default it to the sort you want or simply override it if you don't want to allow a sort to be passed in.

if (pageable.getSort == Sort.unsorted()) {
    List<Sort.Order> orders = new ArrayList<>();
    orders.add(new Sort.Order(Sort.Direction.ASC, "name").ignoreCase()); 
    pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), Sort.by(orders));
}
        
Page<Student> studentPage = studentRepository.findByGraduatedIsNull(status, pageable)
Timon de Groot
  • 7,255
  • 4
  • 23
  • 38
Ed R.
  • 1
  • 4