You are currently viewing Implementing Pagination in Spring Boot

Implementing Pagination in Spring Boot

Pagination is a crucial feature for displaying large sets of data in manageable chunks in web applications. Spring Boot makes it straightforward to implement pagination using Spring Data JPA and its Pageable interface. In this tutorial, we’ll go through how to set up pagination in a Spring Boot application with examples.

Prerequisites

  • Basic understanding of Java, Spring Boot, and JPA.
  • Java Development Kit (JDK) installed on your machine.
  • IDE (like IntelliJ IDEA or Eclipse) installed.
  • A basic Spring Boot project set up.

Step 1: Set Up Your Entity

For demonstration purposes, let’s assume we have an entity called Product that we want to paginate.

Product.java

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private double price;
    private String description;

    // Getters and setters (omitted for brevity)
}

Step 2: Create a Repository Interface

Next, create a repository interface for Product that extends JpaRepository. This interface will provide methods for pagination.

ProductRepository.java

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
    Page<Product> findAll(Pageable pageable);
}

Step 3: Implement Pagination in a Service

Now, let’s create a service class that will use the repository to fetch paginated data.

ProductService.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
public class ProductService {

    @Autowired
    private ProductRepository productRepository;

    public Page<Product> getAllProducts(int pageNumber, int pageSize) {
        Pageable pageable = PageRequest.of(pageNumber, pageSize);
        return productRepository.findAll(pageable);
    }
}

Step 4: Create a Controller for Pagination Endpoints

Finally, create a controller to expose pagination endpoints.

ProductController.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping("/products")
    public ResponseEntity<Page<Product>> getProductsPaginated(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        Page<Product> products = productService.getAllProducts(page, size);
        return new ResponseEntity<>(products, HttpStatus.OK);
    }
}

In this controller, we’ve defined an endpoint /products that accepts optional query parameters page and size for pagination. If not provided, it defaults to page 0 and size 10.

Step 5: Test Pagination

You can now test the pagination by running your Spring Boot application and making requests to the /products endpoint with different page and size parameters.

  • GET http://localhost:8080/products?page=0&size=5 – Retrieves the first 5 products.
  • GET http://localhost:8080/products?page=1&size=5 – Retrieves the next 5 products.

Advanced Pagination: Sorting

You can also add sorting to your pagination by modifying the repository method. For example, let’s add a method to the ProductRepository to fetch products sorted by name:

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
    Page<Product> findAllByNameContainingIgnoreCase(String name, Pageable pageable);
}

Then update the ProductService to use this method:

public Page<Product> getAllProductsByName(String name, int pageNumber, int pageSize) {
    Pageable pageable = PageRequest.of(pageNumber, pageSize);
    return productRepository.findAllByNameContainingIgnoreCase(name, pageable);
}

And update the ProductController to expose the new endpoint:

@GetMapping("/productsByName")
public ResponseEntity<Page<Product>> getProductsByName(
        @RequestParam String name,
        @RequestParam(defaultValue = "0") int page,
        @RequestParam(defaultValue = "10") int size
) {
    Page<Product> products = productService.getAllProductsByName(name, page, size);
    return new ResponseEntity<>(products, HttpStatus.OK);
}

Conclusion

In this tutorial, you’ve learned how to implement pagination in a Spring Boot application using Spring Data JPA’s Pageable interface. By following these steps, you can easily retrieve and display paginated data from your database. Additionally, we explored adding sorting functionality to our pagination for more advanced data retrieval. Pagination is a fundamental feature in web applications that improves performance and user experience when dealing with large datasets.

Leave a Reply