Home > Back-end >  Spring Pageable Sort works incorrect with mongoOperations. Sort order isn't correct
Spring Pageable Sort works incorrect with mongoOperations. Sort order isn't correct

Time:09-17

I use org.springframework.data.domain.Pageable to get pagination and sorting rules from Front-End. I need to sort the entries by name, at first glance everything is working correctly now. But, the system gives the character I before the character f. It looks as if the sorting is going well according to table ASCII.

011
Alpha
Itext
front
man

Request looks like ...&sort=title,desc. I get an pagination object and put it in a query in the DB.

return mongoOperations.find(Query.query(criteria).with(pageable), Book.class);

CodePudding user response:

The code is working as intended, it sorts by name case sensitive. You can change the sorting algorithm for example using the following code:

Sort.Order order = new Sort.Order(Direction.ASC, "title").ignoreCase();
Pageable paging = PageRequest.of(page, pageSize, Sort.by(order));
Page<Video> findAll = videoRepo.findAll(paging);

You can use something like this to change the paging you get from your request and making it case insensitive:

Pageable paging = ... // from your request

List<Order> caseInsensitiveOrders = paging.getSort().get().map(Order::ignoreCase).collect(Collectors.toList());
Pageable newPaging = PageRequest.of(page, pageSize, Sort.by(caseInsensitiveOrders));
Page<Video> findAll = videoRepo.findAll(newPaging);

The key is using order.ignoreCase();

  • Related