Append default order by id to Pageable with Spring Data
19,774
Solution 1
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
Solution 2
Add Sort and direction with @PageableDefault:
public String printMensagges(@PageableDefault(size = 40, sort = "id", direction = Direction.DESC) Pageable pageable, Model model)
Author by
oscar
Updated on June 23, 2022Comments
-
oscar almost 2 years
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?
-
zbender over 3 yearsThis is not what the author of the question wants. The essence of the problem is that each time it is necessary to additionally add an identifier (by the last level) to the sorting.