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?
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
Add Sort and direction with @PageableDefault:
public String printMensagges(@PageableDefault(size = 40, sort = "id", direction = Direction.DESC) Pageable pageable, Model model)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With