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>();
query.orderBy(cb.asc(root.get("surname")));
for (String field : stringFilterMap.keySet()) {
String valuePattern = stringFilterMap.get(field);
predicates.add(cb.like(root.get(field), "%"+valuePattern+"%"));
}
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.
, , , .
; ?