Spring Boot Tutorial, Spring boot docs github, Spring boot docs example, Spring boot docs tutorial, Spring Initializr, Spring Boot profiles, Spring Boot initializr, Spring Boot interview questions
|

Spring Boot Pagination with Sorting: Complete Guide PageRequest.of

Pageable vs slice in spring boot when to use what java, Pageable Spring Boot, Spring Boot pagination with custom query, Spring Boot pagination, sorting and filtering, Spring Data Slice example, Pagination and sorting in Spring Boot REST API, Pagination in Spring Boot REST API with JPA, Server side pagination in Spring Boot

Efficient data handling is a critical aspect of web application development. Pagination combined with sorting not only improves performance but also enhances user experience by fetching data in a structured and meaningful way. Adding sorting to paginated results enables users to organize their data the way they need it, making applications more intuitive and tailored.

This guide provides a complete walkthrough for implementing pagination with sorting in Spring Boot, covering everything from basic setup to advanced techniques for optimizing performance.

Table of Contents

  1. Importance of Sorting in Paginated Results
  2. Using PageRequest.of(page, size, Sort.by(…))
  3. ASC vs DESC and Multiple Field Sorting
  4. Customizing Default Sort Direction
  5. Pagination + Sorting in Repository Method
  6. Exposing Sorting via REST Query Params
  7. Integrating Pagination with Spring Data REST
  8. Using PageableHandlerMethodArgumentResolver
  9. Real-World Use Case Example
  10. Tips for Performance and Scalability
  11. FAQs

Importance of Sorting in Paginated Results

Sorting, when paired with pagination, provides users with the ability to organize large data outputs meaningfully. Here’s why it’s crucial:

  1. Improved Usability: Users can sort data (e.g., by name, price, or date) to quickly locate the information they need.
  2. Optimized Query Outputs: Sorting allows databases to intelligently retrieve only the most relevant data in the requested order.
  3. Better Control: Developers can expose sorting controls to users while maintaining high performance by querying in small chunks (pages).

Imagine an e-commerce website where customers can browse through thousands of products and sort them by price or rating. Without sorting (and pagination), such a system would become unusable as datasets grow.


Using PageRequest.of(page, size, Sort.by(...))

Spring Boot provides the PageRequest.of() method to handle pagination and sorting effortlessly. The Sort.by(...) method is used to specify sorting behavior.

Syntax Example:

Here’s how to create a PageRequest with pagination and sorting:

PageRequest pageRequest = PageRequest.of(
    0,                                           // Page number (0-based index)
    10,                                          // Page size
    Sort.by(Sort.Direction.ASC, "propertyName")  // Sorting on `propertyName`
);

Code in Context:

Integrate it into a controller:

public Page<Product> getSortedProducts(int page, int size) {
    PageRequest pageRequest = PageRequest.of(page, size, Sort.by("price"));
    return productRepository.findAll(pageRequest);
}

This setup retrieves the first page of 10 products sorted by price in ascending order.

For more on PageRequest, refer to the Spring Data JPA Reference.


ASC vs DESC and Multiple Field Sorting

Sorting direction matters. Default ascending (ASC) orders from smallest to largest (e.g., A to Z), while descending (DESC) reverses the order.

Code for Direction:

Sort ascendingSort = Sort.by(Sort.Direction.ASC, "name");
Sort descendingSort = Sort.by(Sort.Direction.DESC, "price");

Multiple Field Sorting:

Combine multiple sort criteria:

Sort multiSort = Sort.by(
    Sort.Order.asc("category"),
    Sort.Order.desc("price")
);

This sorts first by category (ascending) and then by price (descending).

Practical Uses:

  1. E-commerce sorting by category and price.
  2. Blog posts ordered by published date and popularity.

Customizing Default Sort Direction

By default, if no sort parameter is provided, Spring sorts in ascending order. To customize this behavior:

Custom Defaults in Code:

Modify your service layer:

public Page<Product> getProductsWithDefaultSort(Pageable pageable) {
    if (!pageable.getSort().isSorted()) {  // Check if no sort is provided
        pageable = PageRequest.of(
            pageable.getPageNumber(),
            pageable.getPageSize(),
            Sort.by("defaultField").descending()
        );
    }
    return productRepository.findAll(pageable);
}

This ensures that all responses include a predefined sort order.


Pagination + Sorting in Repository Method

Spring Data JPA allows you to integrate sorting directly into custom repository methods using the Pageable parameter.

Example:

@Query("SELECT p FROM Product p WHERE p.category = :category")
Page<Product> findByCategory(
    @Param("category") String category,
    Pageable pageable
);

Explanation:

  • Filter by category.
  • Apply both pagination and sorting.

Exposing Sorting via REST Query Params

REST APIs allow users to customize page size, number, and sorting through query parameters.

Example Request:

GET /products?page=0&size=10&sort=price,asc

Code Example:

Setup a REST API to parse parameters:

@GetMapping
public Page<Product> getProducts(
    @RequestParam(defaultValue = "0") int page,
    @RequestParam(defaultValue = "10") int size,
    @RequestParam(defaultValue = "name,asc") String[] sort
) {
    Sort.Direction direction = Sort.Direction.fromString(sort[1]);
    Sort sortOrder = Sort.by(direction, sort[0]);
    Pageable pageable = PageRequest.of(page, size, sortOrder);
    return productRepository.findAll(pageable);
}

Users gain more flexibility by customizing the sorting and pagination behavior through APIs.


Integrating Pagination with Spring Data REST

Spring Data REST automatically supports pagination and sorting for repository-based REST endpoints.

How to Enable:

  1. Add Spring Data REST Dependency:
   implementation 'org.springframework.boot:spring-boot-starter-data-rest'
  1. Access endpoints with query parameters, such as:
   GET /products?page=1&size=5&sort=price,DESC

Using PageableHandlerMethodArgumentResolver

Spring simplifies pagination and sorting through the PageableHandlerMethodArgumentResolver, which automatically maps query parameters to Pageable.

How to Integrate:

Inject the resolver:

@Configuration
@EnableWebMvc
public class PageableConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(new PageableHandlerMethodArgumentResolver());
    }
}

This lets you directly use Pageable in controller endpoints.


Real-World Use Case Example

Imagine a blog platform where users can sort posts by date, popularity, or author while paginating through results.

Example Implementation:

API Endpoint:

@GetMapping("/posts")
public Page<Post> getPosts(Pageable pageable) {
    return postRepository.findAll(pageable);
}

Sample Query:

GET /posts?page=0&size=5&sort=date,DESC

Tips for Performance and Scalability

  1. Database Indexing: Use indexes on columns often used for sorting.
  2. Client-Side Caching: Cache paginated results on the client-side to reduce repeated fetches.
  3. Optimize Queries: Limit maximum page size and avoid fetching unnecessary fields.
  4. Testing: Test with large datasets using tools like Postman or Swagger.

FAQs

Q1. What is the difference between pagination and sorting?

Pagination retrieves subsets of data, while sorting organizes them in a specific order.

Q2. Can I download all pages at once?

It’s inefficient. Consider implementing batch exports instead.

Q3. How can I secure sorting parameters?

Whitelist sortable fields and validate inputs to avoid SQL injection risks.

Q4. Is Spring Boot pagination only for databases?

No, you can paginate other datasets (e.g., in-memory lists).

Mastering pagination with sorting in Spring Boot empowers developers to create scalable, user-friendly APIs. Experiment, refine, and watch your application transform!

Pageable vs slice in spring boot when to use what java

Pageable Spring Boot

Spring Boot pagination with custom query

Spring Boot pagination, sorting and filtering

Spring Data Slice example

Pagination and sorting in Spring Boot REST API

Pagination in Spring Boot REST API with JPA

Server side pagination in Spring Boot

Similar Posts