Sunday, December 29, 2024
Google search engine
HomeLanguagesJavaSpring – REST Pagination

Spring – REST Pagination

Spring Framework is built on top of servlets. This particular web framework comes with very essential features with which we can develop efficient and effective web applications. On top of Spring Framework, Spring Boot was released in April 2014. The main aim behind the Spring Boot was the feature of Auto-Configuration. Spring MVC ( Model View Controller ) is the sub-domain or sub-project of the Spring Framework which is embedded in Spring’s ‘Web Starter’ dependency. It is used for developing web applications. Web Starter also contains features for developing REST API. We use it to return the data or list of data instead of the HTML pages.
The data which is retrieved from a data source can be very large that it will be inconvenient to list all of them, that too directly. This retrieved or returned data can be controlled in a number of ways. For example, to limit the entities or objects return, the way they are sorted, etc. Here, Pagination comes into action.

Spring - REST Pagination

Features of the Pagination

  1. Limit output to the respective set of items.
  2. Can traverse from one set of items to another set.
  3. Can handle the large offsets of data values.
  4. The output can be ordered. For eg – Ascending or Descending according to some property.

Working of Pagination using Spring’s REST API 

Project Structure – Maven

A. File: pom.xml (Configuration of the application)

XML




<?xml version="1.0" encoding="UTF-8"?>
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>sia</groupId>
    <artifactId>GFG-Pagination</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>GFG-Pagination</name>
    <description>GFG</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


B. GfgPaginationApplication.java 

Java




// Java Program to Illustrate Bootstrapping of Application
 
package gfg;
 
// Importing required classes
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
// Annotation
@SpringBootApplication
// Class
public class GfgPaginationApplication {
 
    // Main driver method
    public static void main(String[] args)
    {
        SpringApplication.run(
            GfgPaginationApplication.class, args);
    }
}


C. application.properties ( Configuration of the Properties )

  • This file contains all the properties and their values that are required to build a Datasource object.
  • The Datasource object is provided by the ‘Spring Data JPA’ dependency.
  • The Spring Data JPA has the default implementation of the Hibernate.
  • This file also contains some Hibernate properties.
  • The Datasource object built is then used by the MySQL Driver to connect to the database.
  • Therefore, we can also interact with the respective database.

Overview of MySQL database entity entries

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/userdetails
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

D. UserEntity.java 

This class is mapped to a table in a database.

1. Persistence Annotations:

  • @Entity – It specifies that the class is an Entity. The ‘name’ attribute is used to map the Class name to the table name in the database if they are not the same.
  • @Id – It specifies that the property it is applied on acts as a primary key for the respective table with which we can access the database.

2. Lombok Annotations

  • @Data – It automatically generates Getter and Setter methods for all the fields at runtime.
  • @RequiredArgsConstructor – It generates constructors for all required fields i.e The fields with keyword final or @NonNull annotation. If no such fields are present then a zero arguments constructor is created. This annotation is a part of @Data annotation.

The object of this class will be returned as a JSON response by the REST API.

Example:

Java




// Java Program to Illustrate Model Data
 
package gfg;
 
// Importing required classes
import javax.persistence.Entity;
import javax.persistence.Id;
import lombok.Data;
import lombok.RequiredArgsConstructor;
 
// Annotation
@Data
@RequiredArgsConstructor
@Entity(name = "user")
// Class
public class UserEntity {
 
    @Id String user;
    String username;
    String password;
}


E. File: UserRepository.java

  • This interface is used to work with databases without the need to write the cumbersome JDBC ( Java Database Connectivity ) methods.
  • This interface extends ‘Interface JpaRepository<T, ID>’, Where T is an Object type and ID is the type of a primary key.

Note: JpaRepository has 4 superinterfaces QueryByExampleExecutor<T>, Repository<T,ID>, CrudRepository<T,ID> and PagingAndSortingRepository<T, ID> which is the one that provides essential Pagination features.

CrudRepository provides the generalized JDBC methods which run SQL scripts to interact with the databases.

(Create, Read, Update, Delete).

public interface PagingAndSortingRepository<T,ID>
extends CrudRepository<T,ID>

Methods of  PagingAndSortingRepository interface are as follows: 

Method

Description

Page<T> findAll(Pageable pageable) Returns a Page of entities meeting the paging restriction provided in the Pageable object.
Iterable<T> findAll(Sort sort Returns all entities sorted by the given options.

Example:

Java




// Java Program to Illustrate Data Repository
 
package gfg;
 
// Importing required classes
import org.springframework.data.jpa.repository.JpaRepository;
 
// Interface
public interface UserRepository
    extends JpaRepository<UserEntity, String> {
}


F. File: PagedRestController.java

  • This controller class returns a list of UserEntities objects as a response.
  • Here, a Pageable object is created using PageRequest.of() factory method.
  • This method accepts 3 arguments:
  1. A number of a respective page.
  2. Number of entries to retrieve per page.
  3. Sorting technique.

This object of Pageable is passed to the findAll() method of PagingAndSortingRepository<T, ID> which accepts the same respective object and returns a Page object. Then the items retrieved from the Page object are eventually returned.

Example:

Java




// Java Program to Illustrate REST API
 
package gfg;
 
// Importing required classes
import java.util.List;
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.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
@RequestMapping("/get")
public class PagedRestController {
 
    // links automatically created repository bean in
    // Spring Application context
    @Autowired UserRepository data;
 
    @GetMapping("/page-One")
    public List<UserEntity> getPageOne()
    {
 
        // First page with 5 items
        Pageable paging = PageRequest.of(
            0, 5, Sort.by("user").ascending());
        Page<UserEntity> page = data.findAll(paging);
 
        // Retrieve the items
        return page.getContent();
    }
 
    @GetMapping("/page-Two")
    public List<UserEntity> getPageTwo()
    {
 
        // Second page with another 5 items
        Pageable paging = PageRequest.of(
            1, 5, Sort.by("user").ascending());
        Page<UserEntity> page = data.findAll(paging);
 
        // Retrieve the items
        return page.getContent();
    }
}


Output 1:

Items in First Page

Output 2:

Items in Second Page

Conclusion:

  1. As most industries work with large datasets, REST APIs are very popular and widely used as they help in returning data responses.
  2. Therefore, for them, Pagination becomes a very crucial feature for them to apply.
  3. It also helps to build a good and manageable UI ( User Interface).
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments