Pagination and Sorting
Do not load everything at once
If a table contains thousands of rows, a method that always returns the entire list quickly becomes inconvenient.
Spring Data can pass a Pageable object to a repository:
it describes the page number, page size, and optional sorting.
interface CustomerRepository extends JpaRepository<Customer, Long> {
Page<Customer> findByActiveTrue(Pageable pageable);
}
Pageable pageable = PageRequest.of(
0,
20,
Sort.by("name").ascending()
);
Page<Customer> page = repository.findByActiveTrue(pageable);
This requests the first page with 20 elements, sorted by name.
Page contains not only the elements of the current page,
but also metadata: the total number of elements, the number of pages, and information about neighboring pages.
Page, Slice, and Sort
When the interface really needs the total number of matching rows, Page is convenient.
If it is enough to know whether another chunk of data exists, you can use Slice
and avoid requiring a count of all matching rows.
Sorting can be passed together with Pageable or separately through Sort.
PageRequest.of(0, 20) means the first page, not “page zero” in the user interface.