Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append default order by id to Pageable with Spring Data

I'm using spring Pageable data and objects. When sorting by a field that can have the same values in database, changing page retrieves erroneous results.

I'm trying to add default order by id with HandlerInterceptorAdapter as follows:

My Interceptor:

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;
    }
}

My 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";
}

I get this error:

java.lang.IllegalStateException: JBWEB000096: No modifications are allowed to a locked ParameterMap

Is there any way to add default order ever? Can you add on service methods that have a Pageable parameter?

like image 329
oscar Avatar asked Apr 11 '16 15:04

oscar


2 Answers

Instead of adding a separate @SortDefault, you can just add the sorting in the @PageableDefault definition.

@PageableDefault(sort = {"name", "id"}, direction = Sort.Direction.DESC, value = 5) final Pageable pageable
like image 159
ScottM Avatar answered Sep 30 '22 19:09

ScottM


Add Sort and direction with @PageableDefault:

 public String printMensagges(@PageableDefault(size = 40, sort = "id", direction = Direction.DESC) Pageable pageable, Model model)
like image 30
Sriparna Ghosh Avatar answered Sep 30 '22 18:09

Sriparna Ghosh