java 使用Spring Data将default order by id追加到Pageable

c2e8gylq  于 2023-06-20  发布在  Java
关注(0)|答案(4)|浏览(110)

我正在使用spring Pageable数据和对象。当按数据库中可能具有相同值的字段排序时,更改页面将检索错误的结果。
我尝试使用HandlerInterceptorAdapter添加默认的order by id,如下所示:
我的拦截器:

public class OrderByIdWebArgumentResolver extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        HandlerMethod hm= (HandlerMethod) handler;
        Method method = hm.getMethod();
        OrderById orderById = method.getAnnotation(OrderById.class);
        if (orderById != null) {
            for (MethodParameter parametro : hm.getMethodParameters()) {
                if (parametro.getGenericParameterType().equals(Pageable.class)) {
                    Map<String, String[]> parameters = request.getParameterMap();
                    String[] sortById = new String[2];
                    sortById[0] = "id";
                    sortById[0] = "desc";
                    parameters.put("sort", sortById);
                }

            }

        }

        return true;
    }
}

我的控制器:

@OrderById
@RequestMapping(value = "/print", method = RequestMethod.GET)
public String printMensagges(@ModelAttribute MensaggesOption messageSelector, final ModelMap model,
       @SortDefault(sort = "date", direction = Sort.Direction.DESC) @PageableDefault(value = 5) final Pageable pageable, final Principal principal) {

    //I need the pageable has order by id here or in a service method
    List<Message> messages = messageService.findAll(pageable);

    return "/index";
}

我得到这个错误:
java.lang.IllegalStateException:JBWEB000096:不允许对锁定的ParameterMap进行修改
有没有什么方法可以添加默认顺序?你能添加一个有Pageable参数的服务方法吗?

goucqfw6

goucqfw61#

您可以只在@PageableDefault定义中添加排序,而不是添加单独的@SortDefault。

@PageableDefault(sort = {"name", "id"}, direction = Sort.Direction.DESC, value = 5) final Pageable pageable
tsm1rwdh

tsm1rwdh2#

使用@PageableDefault添加排序和方向:

public String printMensagges(@PageableDefault(size = 40, sort = "id", direction = Direction.DESC) Pageable pageable, Model model)
mfpqipee

mfpqipee3#

这是我的解决方案(与定制字段名称的额外排序)。
可分页参数的注解(用于自定义字段名称):

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface AdditionalSort {
    String value() default "id";
}

配置(此处为问题的主要答案):

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        PageableHandlerMethodArgumentResolver pageResolver =
                new PageableHandlerMethodArgumentResolver(new AdditionalSortHandlerMethodArgumentResolver());
        pageResolver.setFallbackPageable(PageRequest.of(0, Integer.MAX_VALUE));
        argumentResolvers.add(pageResolver);
    }

    private static class AdditionalSortHandlerMethodArgumentResolver extends SortHandlerMethodArgumentResolver {

        private static final String DEFAULT_ADDITIONAL_SORT_FIELD = "id";

        @Override
        public Sort resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                    NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
            Sort sort = super.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
            String additionalSortField = parameter.hasParameterAnnotation(AdditionalSort.class) ?
                    parameter.getParameterAnnotation(AdditionalSort.class).value() : DEFAULT_ADDITIONAL_SORT_FIELD;
            return sort.and(Sort.by(additionalSortField));
        }

    }

}

控制器:

@GetMapping(value = "/byOrganization/{organizationId}", produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<JsonItem<PageDto<EmployeeDto>>> getByOrganization(@PathVariable
                                                                                String organizationId,
                                                                        EmployeeFilter filter,
                                                                        @SortDefault(sort = CREATION_DATE, direction = DESC)
                                                                        @AdditionalSort("personId")
                                                                                Pageable pageable) {
    return ResponseEntity.ok(JsonItem.withData(employeeService.findEmployees(organizationId, filter, pageable)));
}
amrnrhlw

amrnrhlw4#

Spring允许提供多个排序规则,每个规则使用专用的annotation @SortDefault.SortDefaults具有不同的排序方向。请注意,尽管@PageableDefault注解允许多个排序列,但它不允许应用不同的排序方向,而只允许应用于所有列的单个值。

@PageableDefault(size = 30)
  @SortDefault.SortDefaults({
      @SortDefault(
          sort = "createdAt", // column name of underlying DB table
          direction = Sort.Direction.DESC),
      @SortDefault(
          sort = "updatedAt", // column name of underlying DB table
          direction = Sort.Direction.ASC)
  }) Pageable pageable

相关问题