×
☰ See All Chapters

Pagination in Spring Data JPA

Pagination is much important aspect when we have large records and we want to read it page by page. This pagination is very important for performance of an application where it saves memory by reading the data in smaller chunks. In this tutorial, we'll learn how to easily paginate using Spring Data JPA.

How to do pagination with spring data JPA?

  1. Query method in the repository should accept Pageable object as its last parameter. 

public interface  StudentRepository extends CrudRepository<Student, Long>{

                List<Student> findByMarksGreaterThan(Long marks, Pageable pageable);

}

  1. Crete Pageable object. Pageable is an interface which contains requested current page information. Create the Pageable object using PageRequest.  PageRequest implements Pageable. 

Below Table is the list of methods of PageRequest used in pagination with spring data JPA

Method

Description

Pageable first()

Returns the Pageable requesting the first page.

Sort getSort()

Returns the sorting parameters.

Pageable next()

Returns the Pageable requesting the next Page.

static PageRequest of(int page, int size)

Creates a new unsorted PageRequest.

static PageRequest of(int page, int size, Sort.Direction direction, String... properties)

 

Creates a new PageRequest with sort direction and properties applied.

static PageRequest of(int page, int size, Sort sort)

Creates a new PageRequest with sort parameters applied.

PageRequest previous()

Returns the Pageable requesting the previous Page.

 

@Service("studentService")

public class StudentService {

        @Autowired

        private StudentRepository repository;

       

        public List<Student> test(int page, int size) {

                //Pageable pageable = PageRequest.of(page, size, Sort.by("firstName"));

                Pageable pageable = PageRequest.of(page, size);

                return repository.findByMarksGreaterThan(97L, pageable);

        }

}

 

Most commonly used method is PageRequest.of(page, size), it takes two parameters. First is the page number and second is the number of records for that page.

Pagination example in spring data JPA

Below code is an example for pagination in spring data JPA

Database script (MySQL)

CREATE TABLE STUDENT (

       STUDENTID INT NOT NULL AUTO_INCREMENT,

       FIRSTNAME VARCHAR(20) DEFAULT NULL,

       LASTNAME VARCHAR(20) DEFAULT NULL,

       MARKS INT(20) DEFAULT NULL,

       PRIMARY KEY (STUDENTID)

);

 

INSERT INTO STUDENT (FIRSTNAME,LASTNAME,MARKS) VALUES ('Manu','Manjunatha', 100);

INSERT INTO STUDENT (FIRSTNAME,LASTNAME,MARKS) VALUES('Advith','Tyagraj', 100);

INSERT INTO STUDENT (FIRSTNAME,LASTNAME,MARKS) VALUES('Likitha','Tyagraj', 98);

INSERT INTO STUDENT (FIRSTNAME,LASTNAME,MARKS) VALUES('Srinivas','HV', 98);

INSERT INTO STUDENT (FIRSTNAME,LASTNAME,MARKS) VALUES('Manoj','M', 98);

INSERT INTO STUDENT (FIRSTNAME,LASTNAME,MARKS) VALUES('Chethan','SN', 98);

INSERT INTO STUDENT (FIRSTNAME,LASTNAME,MARKS) VALUES('Ganesh','Metro', 98);

 

COMMIT;

pom.xml

<project xmlns="https://maven.apache.org/POM/4.0.0"

        xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"

        xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

        <modelVersion>4.0.0</modelVersion>

        <groupId>com.java4coding</groupId>

        <artifactId>SpringDataJPA_Pagination</artifactId>

        <version>0.0.1-SNAPSHOT</version>

 

        <dependencies>

                <dependency>

                        <groupId>org.springframework</groupId>

                        <artifactId>spring-context</artifactId>

                        <version>5.1.4.RELEASE</version>

                </dependency>

                <dependency>

                        <groupId>org.springframework</groupId>

                        <artifactId>spring-orm</artifactId>

                        <version>5.1.4.RELEASE</version>

                </dependency>

                <dependency>

                        <groupId>org.hibernate</groupId>

                        <artifactId>hibernate-core</artifactId>

                        <version>5.4.1.Final</version>

                </dependency>

                <dependency>

                        <groupId>org.springframework.data</groupId>

                        <artifactId>spring-data-jpa</artifactId>

                        <version>2.1.4.RELEASE</version>

                </dependency>

                <dependency>

                        <groupId>mysql</groupId>

                        <artifactId>mysql-connector-java</artifactId>

                        <version>8.0.14</version>

                </dependency>

        </dependencies>

 

        <build>

                <plugins>

                        <plugin>

                                <groupId>org.apache.maven.plugins</groupId>

                                <artifactId>maven-compiler-plugin</artifactId>

                                <version>3.8.1</version>

                                <configuration>

                                        <source>1.8</source>

                                        <target>1.8</target>

                                </configuration>

                        </plugin>

                </plugins>

        </build>

</project>

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="https://java.sun.com/xml/ns/persistence"

        xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"

        xsi:schemaLocation="https://java.sun.com/xml/ns/persistence

             https://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"

        version="2.0">

 

        <persistence-unit name="StudentPU">

                <provider>org.hibernate.ejb.HibernatePersistence</provider>

                <properties>

                        <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/study" />

                        <property name="hibernate.connection.driver_class" value="com.mysql.cj.jdbc.Driver" />

                        <property name="hibernate.connection.username" value="root" />

                        <property name="hibernate.connection.password" value="root" />

                        <property name="hibernate.archive.autodetection" value="class" />

                        <property name="hibernate.show_sql" value="true" />

                        <property name="hibernate.format_sql" value="true" />

                        <property name="hbm2ddl.auto" value="update" />

                </properties>

        </persistence-unit>

</persistence>

Student.java

package com.java4coding;

 

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

 

@Entity

public class Student {

 

        @Id

        @GeneratedValue(strategy = GenerationType.IDENTITY)

        private Long studentId;

        private String firstName;

        private String lastName;

        private Long marks;

 

        public Student() {

                super();

        }

       

        public Student(String firstName, String lastName, Long marks) {

                super();

                this.firstName = firstName;

                this.lastName = lastName;

                this.marks = marks;

        }

       

        //Setters and getters

        public Long getId() {

                return studentId;

        }

 

        public void setId(Long id) {

                this.studentId = id;

        }

 

        public String getFirstName() {

                return firstName;

        }

 

        public void setFirstName(String firstName) {

                this.firstName = firstName;

        }

 

        public String getLastName() {

                return lastName;

        }

 

        public void setLastName(String lastName) {

                this.lastName = lastName;

        }

       

        public Long getMarks() {

                return marks;

        }

 

        public void setMarks(Long marks) {

                this.marks = marks;

        }

 

        @Override

        public String toString() {

                return "Student [firstName=" + firstName + ", lastName=" + lastName + ", Marks= " + marks + "]";

        }

}

AppConfig.java

package com.java4coding;

 

import javax.persistence.EntityManagerFactory;

 

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import org.springframework.orm.jpa.JpaTransactionManager;

import org.springframework.orm.jpa.LocalEntityManagerFactoryBean;

 

@Configuration

@EnableJpaRepositories(basePackages = {"com.java4coding"})

public class AppConfig {

        @Bean

        public LocalEntityManagerFactoryBean entityManagerFactory() {

                LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();

                factoryBean.setPersistenceUnitName("StudentPU");

               

                return factoryBean;

        }

       

        @Bean

        public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {

                JpaTransactionManager transactionManager = new JpaTransactionManager();

                transactionManager.setEntityManagerFactory(entityManagerFactory);

               

                return transactionManager;

        }       

}

StudentRepository.java

package com.java4coding;

 

import java.util.List;

 

import org.springframework.data.domain.Pageable;

import org.springframework.data.repository.CrudRepository;

 

public interface  StudentRepository extends CrudRepository<Student, Long>{

        List<Student> findByMarksGreaterThan(Long marks, Pageable pageable);

}

StudentService.java

package com.java4coding;

 

import java.util.List;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.PageRequest;

import org.springframework.data.domain.Pageable;

import org.springframework.stereotype.Service;

 

@Service("studentService")

public class StudentService {

        @Autowired

        private StudentRepository repository;

       

        public List<Student> test(int page, int size) {

                //Pageable pageable = PageRequest.of(page, size, Sort.by("firstName"));

                Pageable pageable = PageRequest.of(page, size);

                return repository.findByMarksGreaterThan(97L, pageable);

        }

}

Test.java

package com.java4coding;

 

import java.util.List;

 

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

 

public class Test {

        public static void main(String[] args) {

                AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext();

                appContext.scan("com.java4coding");

                appContext.refresh();

 

                StudentService studentService = (StudentService) appContext.getBean("studentService");

                System.out.println("**************Stuents with ID from 0 to 2*******************");

                List<Student> students =  studentService.test(0, 2);

                students.forEach(student -> System.out.println(student));

               

                System.out.println("**************Stuents with ID from 2 to 4*******************");

                students =  studentService.test(1, 2);

                students.forEach(student -> System.out.println(student));

               

                System.out.println("**************Stuents with ID from 4 to 6*******************");

                students =  studentService.test(3, 2);

                students.forEach(student -> System.out.println(student));

 

                appContext.close();

        }

}

Project directory structure

pagination-in-spring-data-jpa-0
 

Output

**************Stuents with ID from 0 to 2*******************

Hibernate:

    select

        student0_.studentId as studentI1_0_,

        student0_.firstName as firstNam2_0_,

        student0_.lastName as lastName3_0_,

        student0_.marks as marks4_0_

    from

        Student student0_

    where

        student0_.marks>? limit ?

Student [studentId = 1, firstName=Manu, lastName=Manjunatha, Marks= 100]

Student [studentId = 2, firstName=Advith, lastName=Tyagraj, Marks= 100]

**************Stuents with ID from 2 to 4*******************

Hibernate:

    select

        student0_.studentId as studentI1_0_,

        student0_.firstName as firstNam2_0_,

        student0_.lastName as lastName3_0_,

        student0_.marks as marks4_0_

    from

        Student student0_

    where

        student0_.marks>? limit ?, ?

Student [studentId = 3, firstName=Likitha, lastName=Tyagraj, Marks= 98]

Student [studentId = 4, firstName=Srinivas, lastName=HV, Marks= 98]

**************Stuents with ID from 4 to 6*******************

Hibernate:

    select

        student0_.studentId as studentI1_0_,

        student0_.firstName as firstNam2_0_,

        student0_.lastName as lastName3_0_,

        student0_.marks as marks4_0_

    from

        Student student0_

    where

        student0_.marks>? limit ?, ?

Student [studentId = 7, firstName=Ganesh, lastName=Metro, Marks= 98]

 


All Chapters
Author