WebFlux Pagination For Reactive Spring Data

By | September 22, 2018

In this example I’m trying to create wrapper for pagination with reactive code in spring 5. I have created simple rest endpoint for finding all entities using spring web-flux and spring data reactive mongoDB with pagination.

WebFlux Pagination For Reactive Spring Data

In Spring Data 1.0, we have PagingAndSortingRepository which inherits from CrudRepository. In reactive Spring Data, we only have ReactiveSortingRepository which inherits from ReactiveCrudRepository. I’m using Reactive Spring Data MongoDB repositories, but this library do not provide paging in the sense of paging how it’s designed for imperative repositories. Imperative paging requires additional details while fetching a page. Then, how apply pagination in reactive Spring Data? or how could we make pagination in a reactive way?

First, I know that the reactive support in Spring Data does not provide means of a Page return type. But, the Pageable parameter is supported in method signatures passing on limit and offset to the drivers and therefore the store itself, returning a Flux that emits the range requested. So you can still fetch chunks of data yourself by passing a Pageable (PageRequest) to repository query methods, for example:

interface ReactivePersonRepository extends Repository<Person, Long> {
 Flux findByFirstnameOrderByLastname(String firstname, Pageable pageable);
}

Spring Data will apply pagination to the query by translating Pageable to LIMIT and OFFSET.

Second, we can use skip and take methods in reactive support. Flux provides skip and take methods to get pagination support, and you also can use filter and sort to filter and sort the result. But that’s not enough for me, this is not the answer!.

Reference for spring official documentation: Reactive repository usage

Third, You can clone or download my example for the WebFlux Pagination For Reactive Spring Data on this git repository.

In this project, I’m using spring boot 2.0, mongoDB for the database and lombok plugin for simplify getter and setter.

WebFlux Pagination For Reactive Spring Data

Example for usage:

  1. On the service class:
    Mono<Page<Basic>> findAll(Pageable pageable);
  2. On the service implementation class:
    @Autowired
      private PageUtils pageUtils;
    
      @Override
      public Mono<Page<Basic>> findAll(Pageable pageable) {
        Query query = new Query();
        query.with(pageable);
        return pageUtils.toPage(query, pageable, Basic.class);
      }

Leave a Reply

Your email address will not be published. Required fields are marked *