Spring JPA specification with sorting

I am using Spring JPA.

To be more precise, I use a repository that extends JpaRepositoryand JpaSpecificationExecutorbecause I need pagination, filtering and sorting.

Now I have pagination and filtering, everything works fine, but I can't sort either.

I notice with some disappointment that it JpaSpecificationExecutorhas methods findAll():

findAll(Specification, Pageable);
findAll(Specification, Sort);

But the one I need:

findAll(Specification, Pageable, Sort); //or something like this

does not exist!

So, plan B, include Sort in Specifications.

With the accepted answer to this question: JpaSpecificationExecutor JOIN + ORDER BY in the specification I put together the following:

private Specification<MainEntity> matches() {
    return new Specification<MainEntity>() {

        public Predicate toPredicate(Root<MainEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

            List<Predicate> predicates = new ArrayList<Predicate>();

            //Attempt to sort by Surname, has no effect
            query.orderBy(cb.asc(root.get("surname")));

            //add string filters
            for (String field : stringFilterMap.keySet()) {
                String valuePattern = stringFilterMap.get(field);
                predicates.add(cb.like(root.get(field), "%"+valuePattern+"%"));
            }

            //...snip...

            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        }
    };      
}

Where springFilterMapis the instance field Map<String,String>, whose keys are field names and values ​​are filter values.

, , , .

; ?

+4
1

PageRequest, Pageable, , . , :

public PageRequest(int page, int size, Sort sort)
+7

Source: https://habr.com/ru/post/1673231/


All Articles