I am writing server side pagination code. I am using the findAll() method with Specification to get back filtered and sorted results. Everything works fine but now I have a new requirement. I will be given an array list of integers and I would like my findAll() method to return results sorted on a database column in the order of the list of integers provided.
My specification class looks something like this:
public static Specification<YourEntity> withSearchCriteria(String searchCriteria) {
return (root, query, builder) -> {
Predicate predicate = builder.like(root.get("name"), "%" + searchCriteria + "%");
// more predicate logic
return builder.and(predicate);
};
}
And im calling it like this in my service class: (currently its implemented with basic sort and it works fine)
Sort.Order sortOrder = new Sort.Order(Sort.Direction.ASC, "id");
Sort sort = Sort.by(sortOrder);
Pageable pageable = PageRequest.of(0, 10, sort);
Specification<YourEntity> spec = YourEntitySpecifications.withSearchCriteria(searchCriteria);
return yourEntityRepository.findAll(spec, pageable);
I have tried looking at writing custom sorting for Pageable and criteria builder but I have had no luck on how to implement it.
So my questions are, where should I put the custom sorting logic, within Pageable or within my Specification logic?
And how would I implement the logic based on my requirement?