【问题标题】:Spring JPA Specification with Sort带有排序的 Spring JPA 规范
【发布时间】:2017-08-19 02:25:39
【问题描述】:

我正在使用 Spring JPA。

更准确地说,我使用的是扩展 JpaRepositoryJpaSpecificationExecutor 的存储库,因为我需要分页、过滤和排序。

现在我的分页和过滤都可以正常工作,但我不能让排序也正常工作。

我有些失望地注意到 JpaSpecificationExecutorfindAll() 方法:

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()]));
        }
    };      
}

其中springFilterMap 是实例字段,Map&lt;String,String&gt; 的键是字段名称,值是过滤器值。

您会在上方看到我尝试按姓氏排序,但这似乎没有效果。

我做错了什么;以及如何实现排序以及分页和过滤?

【问题讨论】:

  • 你介意使用 spring query dsl 吗?您不需要编写任何代码进行排序。跟随 spring doc 或者我可以给出一些方向。我已经使用了它,它明确地避免了额外的编码。你只需传入你的参数和 asc/desc ,它会给你适当的结果
  • 我在寻找类似问题时遇到了您的问题。我在我的 Controller 中使用存储库,当使用 Controller 时,您可以在方法签名中使用 @PageableDefault(size = 10, sort = "sortColumn", direction = Sort.Direction.DESC) Pageable pageable 来获取自动填充的 Pageable 对象(就像 @PathVariable 一样)。

标签: java spring sorting spring-data-jpa jpa-criteria


【解决方案1】:

使用PageRequest,它是Pageable 的一个实现,同时实现分页和排序,如你所愿。例如通过this constructor

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

更新: 由于 Spring Data JPA 2.0 已弃用上述构造函数,您应该使用静态工厂方法of

public static PageRequest of(int page, int size, Sort sort)

【讨论】:

  • 是在页面内部进行排序,还是对存储库中的数据进行排序然后分页?
猜你喜欢
  • 1970-01-01
  • 2020-01-11
  • 2020-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-22
  • 1970-01-01
  • 2023-02-19
相关资源
最近更新 更多