Pagination is a technique used to divide large amounts of data into smaller, manageable pages. Instead of displaying all records at once, applications show a limited number of records per page, improving performance and user experience. In Spring MVC, pagination can be implemented easily using Spring Data repositories such as PagingAndSortingRepository or JpaRepository.
- Improves application performance by loading only the required records.
- Enhances user experience when displaying large datasets.
- Supports page-based data retrieval using Spring Data JPA repositories.
Methods to Implement Pagination
Spring applications generally support two approaches:
1. Custom Pagination
- This approach provides complete control over paging behavior.
- Pagination is implemented manually using SQL queries with OFFSET and LIMIT
2. Repository-Based Pagination
- This is the most commonly used approach because it requires minimal code.
- Pagination is handled by Spring Data repositories such as PagingAndSortingRepository and JpaRepository
How PagingAndSortingRepository Works
The PagingAndSortingRepository interface is a Spring Data JPA repository that extends CrudRepository and provides built-in support for pagination and sorting. Instead of writing custom SQL queries, you can retrieve paginated or sorted data using its predefined methods.
@NoRepositoryBean
public interface PagingAndSortingRepository<T, ID>
extends CrudRepository<T, ID> {
Iterable<T> findAll(Sort sort);
Page<T> findAll(Pageable pageable);
}
The findAll(Pageable pageable) method returns paginated data based on the supplied page number and page size.
Note: PagingAndSortingRepository is commonly used for pagination, while JpaRepository extends it and provides additional JPA-specific features. In most modern Spring Boot applications, developers prefer using JpaRepository
Steps to Implement Pagination in Spring MVC
Follow the steps below to create a Spring MVC application with pagination support.
Step 1: Create a Maven Project
- Open STS IDE.
- Click File - New - Maven Project.
- Select Create a simple project (Select archetype ) and click Next.
Then Enter the following details:
- Group Id: com.gfg
- Artifact Id: SpringMVCPagination
- Packaging: war
Click Finish.
Step 2: Add Required Dependencies
Add the following maven dependencies and plugin to your pom.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gfg</groupId>
<artifactId>SpringMVCPagination</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>SpringMVCPagination</name>
<properties>
<java.version>1.8</java.version>
<spring.version>5.3.39</spring.version>
<hibernate.version>5.6.15.Final</hibernate.version>
</properties>
<dependencies>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring Context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.7.18</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- MySQL Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<!-- JPA API -->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
<!-- Servlet API -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Tomcat Jasper -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.98</version>
</dependency>
<!-- JUnit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!-- Spring Test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>SpringMVCPagination</finalName>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.4.0</version>
</plugin>
</plugins>
</build>
</project>
Step 3: Create Entity Class (Product.java)
The Product entity represents product information stored in the database it maps product records to database rows and Stores product details and transfer the data between layers.
package com.geeksforgeeks.Spring.MVC.Pagination.data;
import lombok.Data;
import javax.persistence.*;
@Entity
@Table
@Data
public class Product {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "price")
private int price;
@Column(name = "name")
private String name;
}
Step 4: Create Repository Layer
The repository layer communicates with the database and provides built-in pagination support it fetch product records from the database and support paging and sorting operations and reduce boilerplate database code.
package com.geeksforgeeks.Spring.MVC.Pagination.repositories;
import com.geeksforgeeks.Spring.MVC.Pagination.data.Product;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
// we can also extend from JpaRepository here
@Repository
public interface ProductRepository extends PagingAndSortingRepository<Product,Integer> {
}
Step 5: Create Service Layer
The service layer contains business logic and retrieves paginated data using the repository it process product-related operations and retrieve products page by page and interact with the repository layer.
package com.geeksforgeeks.Spring.MVC.Pagination.services;
import com.geeksforgeeks.Spring.MVC.Pagination.data.Product;
import com.geeksforgeeks.Spring.MVC.Pagination.repositories.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
public void saveAllProducts(List<Product>products){
productRepository.saveAll(products);
}
public Iterable<Product> getAllProducts(Integer pageSize,Integer offset) {
return productRepository.findAll(PageRequest.of(offset,pageSize));
}
}
Step 6: Create Controller Layer
The controller receives HTTP requests and returns paginated product data it accept page number and page size and call service methods to return paginated results.
package com.geeksforgeeks.Spring.MVC.Pagination.controllers;
import com.geeksforgeeks.Spring.MVC.Pagination.data.Product;
import com.geeksforgeeks.Spring.MVC.Pagination.services.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.PostConstruct;
import javax.websocket.server.PathParam;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping
public class ProductController {
@Autowired
private ProductService productService;
@PostConstruct
public void createProducts(){
List<Product>products = new ArrayList<>();
for(int i=0;i<100;i++){
Product product = new Product();
product.setPrice(i);
product.setName("product+"+ i);
products.add(product);
}
productService.saveAllProducts(products);
}
@GetMapping("/getAll/{offset}")
public Iterable<Product> getAllProducts(@RequestParam Integer pageSize, @PathVariable("offset") Integer offset){
return productService.getAllProducts(pageSize,offset);
}
}
Step 7: Run the Application
- Right-click the project.
- Select Run As -> Run on Server.
- Choose Apache Tomcat Server.
- Click Finish.
After that use the following URL to run your controller.
http://localhost:8080/SpringMVCPagination/getAll/1?pageSize=10
Output:
The JSON Response from the backend will look like this
