Spring扩展了PagingAndSortingRepository排序顺序

时间:2015-03-11 15:31:07

标签: spring spring-mvc spring-data

我目前正在实施扩展Spring CustomRepository的{​​{1}},因为我需要在此存储库中按PagingAndSortingRepository排序功能。

一切都按预期工作我在下面有一个生成的休息库: String name

当我想通过url对它进行排序时: http://localhost:8080/app/customrepository{?page,size,sort} 它正在排序,但在大小写敏感的顺序。问题是我需要案例不敏感的排序。有没有办法在没有自定义处理器的情况下实现这一目标?

我使用以下网址获取知识: http://docs.spring.io/spring-data/rest/docs/2.3.0.BUILD-SNAPSHOT/reference/html/#repository-resources.collection-resource

2 个答案:

答案 0 :(得分:3)

目前不支持这主要是因为转换排序HTTP请求参数的组件仅考虑属性名称和方向。我已经为您提交DATACMNS-658以跟踪此要求。

作为一种解决方法,您可以编写一个方面来拦截对要执行的案例忽略排序的查询方法的调用:

@Aspect
static class SortManipulatingAspect {

  /**
   * Intercept all calls to repositories. Might wanna be more specific in the
   * pointcut to maker sure you don't unnecessarily intercept methods without
   * a Sort.
   */
  @Around("execution(public * org.springframework.data.repository.Repository+.*(..))")
  public Object enableIgnoreCaseSorting(ProceedingJoinPoint joinPoint) throws Throwable {
    return joinPoint.proceed(
      Arrays.stream(joinPoint.getArgs()).map(sortWithIgnoreCase()).toArray()
    );
  }

  private static Function<Object, Object> sortWithIgnoreCase() {

    return (arg) -> arg instanceof Sort ? new Sort(
      toOrderStream((Sort) arg).
      // Insert filter here to be selective about which orders to actually
      // activate ignore-case on.
      map(order -> order.ignoreCase()).//
      collect(Collectors.toList())) : arg;
    }

  private static Stream<Order> toOrderStream(Sort sort) {
    return StreamSupport.stream(sort.spliterator(), false);
  }
}

如果你声明make这个类是一个Spring bean(通过组件扫描或显式注册接收),所有Sort个实例都将被忽略 - 大小写被激活。

答案 1 :(得分:0)

有两种方法,在两种情况下,您都需要扩展Spring的默认行为

1-扩展存储库接口(https://medium.com/@ghahremani/extending-default-spring-data-repository-methods-patch-example-a23c07c35bf9)的spring基类

2-或扩展Pageable处理程序(https://medium.com/@ghahremani/pageable-and-sort-in-webflux-c6f6c598537a),请注意:这是用于响应式编程,但是概念相同,您将了解如何扩展Pageable处理程序。