我目前正在实现一个扩展Spring PagingAndSortingRepository的CustomRepository,因为我需要在这个存储库中使用String name排序功能。
一切都如我所愿,我有一个生成的rest存储库:http://localhost:8080/app/customrepository{?page,size,sort}
当我想要通过url对它进行排序时,例如:http://localhost:8080/app/customrepository?sort=name,asc,它会按区分大小写的顺序进行排序。问题是我需要不区分大小写的排序。有没有办法在没有定制处理器的情况下实现这一点?
我使用以下网址获取知识:http://docs.spring.io/spring-data/rest/docs/2.3.0.BUILD-SNAPSHOT/reference/html/#repository-resources.collection-resource
发布于 2015-03-12 20:06:35
目前不支持这一点,主要是因为转换排序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实例都将被激活。
发布于 2020-01-22 22:37:28
在这两种情况下,您都需要扩展Spring的默认行为
1-扩展存储库接口的spring基类(https://medium.com/@ghahremani/extending-default-spring-data-repository-methods-patch-example-a23c07c35bf9)
2-或扩展可分页处理程序(https://medium.com/@ghahremani/pageable-and-sort-in-webflux-c6f6c598537a),注:这是用于反应式编程,但概念是相同的,您将理解如何扩展可分页处理程序。
https://stackoverflow.com/questions/28990810
复制相似问题