Ruben Nagoga Ruben Nagoga - 10 months ago 59
Java Question

Optional pagination with Spring

I am pretty new to java and spring.

What I want to implement is api endpoint

with pagination and sorting. I made it and it works. But also what I would like to do is to return plain list of all tickets if
are not specified in the query params, so in FE I can use that list in selectbox.

What I have tried to do is to implement
on service facade and return list of all tickets. But I didn't find a way how to check if Pageable is set as it always returns default values (size=20, page=0)


@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Page<TicketListItemResponseModel>> getTickets(Pageable pageable) {"> getTickets");
Page<TicketListItemResponseModel> tickets = ticketServiceFacade.getTickets(pageable);"< getTickets");
return new ResponseEntity<>(tickets, HttpStatus.OK);


public Page<TicketListItemResponseModel> getTickets(Pageable pageable) {
Page<Ticket> tickets = ticketService.findAll(pageable);
return ConverterFromPagesToListItem());

public List<TicketListItemResponseModel> getTickets() {
List<Ticket> tickets = ticketService.findAll();
.map(t ->, TicketListItemResponseModel.class))

Perhaps I do it totally wrong?

Answer Source

If you build out your controller method like so, you can manage whether or not you want to implement paging by checking the request params:

public ResponseEntity<Page<TicketListItemResponseModel>> getTickets(
        @RequestParam(value = "page", defaultValue = "0", required = false) int page,
        @RequestParam(value = "count", defaultValue = "10", required = false) int size,
        @RequestParam(value = "order", defaultValue = "ASC", required = false) Sort.Direction direction,
        @RequestParam(value = "sort", defaultValue = "name", required = false) String sortProperty) {
    // here you would check your request params and decide whether or not to do paging and then return what you need to return

If you need to build a PageRequest to pass into your service method, you can do so manually like so:

new PageRequest(page, size, new Sort(direction, sortProperty));