我正在使用 spring Pageable 数据和对象。当按数据库中可以具有相同值的字段排序时,更改页面会检索错误的结果。

我正在尝试使用 HandlerInterceptorAdapter 按 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;
    }
}

我的 Controller :
@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";
}

我收到此错误:



有没有办法添加默认订单?您可以添加具有 Pageable 参数的服务方法吗?

最佳答案

无需添加单独的 @SortDefault,您只需在 @PageableDefault 定义中添加排序即可。

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

关于java - 使用 Spring Data 按 id 将默认顺序附加到 Pageable,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36552396/

10-10 04:44