java Spring JPA 规范与排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43028457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring JPA Specification with Sort
提问by NickJ
I am using Spring JPA.
我正在使用 Spring JPA。
To be more precise I am using a Repository which extends JpaRepository
and JpaSpecificationExecutor
because I require pagination, filtering and sorting.
为了更精确,我使用其延伸的储存库JpaRepository
和JpaSpecificationExecutor
因为我需要分页,过滤和排序。
Now I have the pagination and filtering all working just fine, but I cannot get sorting to work as well.
现在我的分页和过滤都可以正常工作,但我也无法进行排序。
I notice with some disappointment that JpaSpecificationExecutor
has findAll()
methods:
我有些失望地注意到JpaSpecificationExecutor
有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 Sorting in the Specification.
因此,计划 B 在规范中包括排序。
With the help of the Accepted Answer to this question: JpaSpecificationExecutor JOIN + ORDER BY in SpecificationI put together the following:
在此问题的已接受答案的帮助下: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()]));
}
};
}
Where springFilterMap
is an instance field, Map<String,String>
whose keys are field names and values are filters values.
其中springFilterMap
是一个实例字段,Map<String,String>
其键是字段名称,值是过滤器值。
Above you will see my attempt to order by Surname, but this seems to have no effect.
在上面你会看到我尝试按姓氏排序,但这似乎没有效果。
What am I doing wrong; & how can I achieve Sorting along with Pagination and Filtering?
我究竟做错了什么; 以及如何实现排序以及分页和过滤?
回答by Robert Niestroj
Use PageRequest, which is an implementation of Pageable, and implements paging and sorting at once, like you want it. For example through this constructor:
使用PageRequest,它是Pageable 的一个实现,并且一次实现分页和排序,就像你想要的那样。例如通过这个构造函数:
public PageRequest(int page, int size, Sort sort)
UPDATE: Since Spring Data JPA 2.0 the above constructor is deprecated and you should use the static factory method of:
更新:由于春季数据JPA 2.0以上的构造已被废弃,你应该使用静态工厂方法的:
public static PageRequest of(int page, int size, Sort sort)