Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How apply pagination in reactive Spring Data?

Tags:

In Spring Data, we have PagingAndSortingRepository which inherits from CrudRepository. In reactive Spring Data, we only have ReactiveSortingRepository which inherits from ReactiveCrudRepository. How could we make pagination in a reactive way ? Will we able to make this in future with ReactivePagingAndSortingRepository for instance?

like image 267
Steph Avatar asked Sep 23 '17 21:09

Steph


People also ask

How is pagination implemented?

For example, you can implement pagination using links to new pages on your ecommerce site, or using JavaScript to update the current page. Load more and infinite scroll are generally implemented using JavaScript.


1 Answers

Reactive Spring Data MongoDB repositories 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. In particular:

  • The number of returned records for a paging query
  • Optionally, total count of records the query yields if the number of returned records is zero or matches the page size to calculate the overall number of pages

Both aspects do not fit to the notion of efficient, non-blocking resource usage. Waiting until all records are received (to determine the first chunk of paging details) would remove a huge part of the benefits you get by reactive data access. Additionally, executing a count query is rather expensive, and increases the lag until you're able to process data.

You can still fetch chunks of data yourself by passing a Pageable (PageRequest) to repository query methods:

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

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

References:

  • Reference documentation: Reactive repository usage
like image 74
mp911de Avatar answered Sep 20 '22 11:09

mp911de