我正在使用 Spring JPA。
更准确地说,我使用的是一个扩展的存储库,JpaRepository
因为JpaSpecificationExecutor
我需要分页、过滤和排序。
现在我的分页和过滤都工作得很好,但我不能让排序也能正常工作。
我有些失望地注意到有一些JpaSpecificationExecutor
方法findAll()
:
findAll(Specification, Pageable);
findAll(Specification, Sort);
但我需要的一个:
findAll(Specification, Pageable, Sort); //or something like this
不存在!
所以,计划 B,在规范中包括排序。
在此问题的已接受答案的帮助下:JpaSpecificationExecutor JOIN + ORDER BY in Specification我整理了以下内容:
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()]));
}
};
}
wherespringFilterMap
是一个实例字段,Map<String,String>
其键是字段名称,值是过滤器值。
在上面你会看到我尝试按姓氏订购,但这似乎没有效果。
我究竟做错了什么; 以及如何实现分页和过滤的排序?