Spring Boot HandBook

    Paging and Sorting in Spring Data JPA#

    Implementing Pagination and Sorting Using Pageable and Sort Interfaces#

    When working with large datasets, it is essential to retrieve data efficiently. Instead of fetching all records at once, you can paginate and sort the results. Spring Data JPA provides built-in support for pagination and sorting using the Pageable and Sort interfaces.

    1. What is Pagination and Sorting?#

    Pagination is the process of breaking down a large dataset into smaller, manageable pages. Instead of loading all the data in one go, we retrieve one page at a time. This is especially useful for handling large datasets in a memory-efficient way.

    Sorting allows data to be ordered in ascending or descending order based on one or more fields.

    2. The Pageable and Sort Interfaces#

    Spring Data JPA provides the following interfaces for pagination and sorting:

    • Pageable: This interface is used to create pagination information, such as the page number and the number of records per page.
    • Sort: This interface helps to define the sorting logic, such as sorting by a field in ascending or descending order.

    Both of these interfaces can be passed as parameters to repository methods.

    3. Pagination with Pageable#

    Pagination is managed using the Pageable interface. The Pageable object specifies:

    • The page number (zero-based index).
    • The size of the page (number of records per page).

    Repository Method for Pagination#

    Let’s say we have a BookRepository interface extending JpaRepository. The repository provides a method findAll(Pageable pageable) for paginating through books:

    Repository Method for Pagination#

    Let’s say we have a BookRepository interface extending JpaRepository. The repository provides a method findAll(Pageable pageable) for paginating through books:

    public interface BookRepository extends JpaRepository<Book, Long> { }

    Now, you can use the Pageable interface to paginate through the results.

    Example: Paginating Through Books#

    @Autowired private BookRepository bookRepository; public void getPaginatedBooks(int page, int size) { Pageable pageable = PageRequest.of(page, size); Page<Book> bookPage = bookRepository.findAll(pageable); List<Book> books = bookPage.getContent(); // Get the list of books on the current page int totalPages = bookPage.getTotalPages(); // Get total number of pages long totalElements = bookPage.getTotalElements(); // Get total number of elements System.out.println("Total Pages: " + totalPages); System.out.println("Total Elements: " + totalElements); books.forEach(System.out::println); // Print the books on the current page }

    In this example:

    • PageRequest.of(page, size) creates a Pageable object for the specified page number and page size.
    • The Page<Book> object contains the books for that page, along with additional information like total pages and total elements.

    4. Sorting with Sort#

    The Sort interface is used to define sorting criteria for query results. You can sort by one or more fields in ascending or descending order.

    Example: Sorting Books by Title#

    @Autowired private BookRepository bookRepository; public void getSortedBooks() { List<Book> books = bookRepository.findAll(Sort.by("title").ascending()); books.forEach(System.out::println); // Print the sorted books }

    This will sort the books in ascending order by their title field. You can also sort in descending order by using .descending().

    Example: Sorting by Multiple Fields#

    List<Book> books = bookRepository.findAll(Sort.by("author").ascending().and(Sort.by("title").descending()));

    This example first sorts by the author field in ascending order, and if two books have the same author, it sorts by the title field in descending order.

    5. Combining Pagination and Sorting#

    You can combine pagination and sorting by passing both a Pageable object that contains sorting information.

    Example: Paginating and Sorting Books by Title#

    public void getPaginatedAndSortedBooks(int page, int size) { Pageable pageable = PageRequest.of(page, size, Sort.by("title").ascending()); Page<Book> bookPage = bookRepository.findAll(pageable); List<Book> books = bookPage.getContent(); books.forEach(System.out::println); }

    Here, we are paginating the results (with a page size of size) and sorting the books by title in ascending order. The PageRequest.of(page, size, sort) method takes care of both pagination and sorting.

    6. Examples#

    Example 1: Paginating Through Authors#

    public void getPaginatedAuthors(int page, int size) { Pageable pageable = PageRequest.of(page, size); Page<Author> authorPage = authorRepository.findAll(pageable); List<Author> authors = authorPage.getContent(); authors.forEach(System.out::println); }

    Example 2: Sorting Books by Publish Date in Descending Order#

    public void getBooksSortedByPublishDate() { List<Book> books = bookRepository.findAll(Sort.by("publishDate").descending()); books.forEach(System.out::println); }

    Example 3: Paginating and Sorting Authors by Last Name#

    public void getPaginatedAndSortedAuthors(int page, int size) { Pageable pageable = PageRequest.of(page, size, Sort.by("lastName").ascending()); Page<Author> authorPage = authorRepository.findAll(pageable); List<Author> authors = authorPage.getContent(); authors.forEach(System.out::println); }

    In this article, we discussed the implementation of pagination and sorting in Spring Data JPA using the Pageable and Sort interfaces. We explored the importance of efficiently managing large datasets by breaking them into manageable pages and ordering them based on specified fields. By leveraging the built-in capabilities of Spring Data JPA, we demonstrated how to create repository methods for pagination and sorting, as well as how to combine both functionalities for enhanced data retrieval. Understanding and implementing these techniques can significantly improve the performance and user experience of applications dealing with extensive data collections.

    Last updated on Oct 25, 2024