Spring Boot Pagination Sorting
In this tutorial will demonstrate how to use pagination and sorting in spring boot application.
Page vs Slice
According to the Spring Data JPA documentation, Page extends
Slice
and knows the total number of items and pages available by initiating a count query.
A Page
is aware of the entire number of elements and pages that are available. It achieves this by
invoking a count query to calculate the total number. Because this may be costly depending on the
business, Slice
can be used as a return option. A Slice
merely knows whether there is a next Slice
available, which may be adequate for traversing a bigger result set.
Now, let's create the Spring Boot Project from Spring Initializer site https://start.spring.io/.
Refer Spring Data JPA documentation for Paging and Sorting for more details.
Project Structure
Maven Dependency
Addspring-boot-starter-data-jpa
for jpa repository and
spring-boot-starter-web
for rest api's.
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.techgeekenxt</groupId>
<artifactId>spring-boot-pagination-sorting</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-pagination-sorting</name>
<description>Spring Boot Pagination Sorting Example</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
Take a look at our suggested posts:
User JPA Entity
Create User entity class which represent user records in database.
package com.techgeeknext.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name="USERS")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String lastName;
@Column(name="status", nullable=false, length=200)
private String status;
}
Repository
PagingAndSortingRepository
interface extends CrudRepository
for retrieving
entities,it provides methods such as count , delete , deleteAll , deleteById , existsById ,
findAll , findAllById , findById , save , saveAll.
package com.techgeeknext.repository;
import com.techgeeknext.model.User;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository
extends PagingAndSortingRepository<User, Long> {
}
The act of loading one page of objects after another from a database in order to save resources is known as Paging.
Pagination is a user interface element that displays a list of page numbers to allow the user to select which page to load next.
User Service Class for Pagination and Sorting
Use findAll()
method to do pagination and sorting.
package com.techgeeknext.service;
import com.techgeeknext.exception.UserNotFoundException;
import com.techgeeknext.model.User;
import com.techgeeknext.repository.UserRepository;
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.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class UserService {
@Autowired
UserRepository userRepository;
public List<User> getAllUsers(Integer pageNo, Integer pageSize, String sortBy) {
Pageable paging = PageRequest.of(pageNo, pageSize, Sort.by(sortBy));
Page<User> pagedResult = userRepository.findAll(paging);
if (pagedResult.hasContent()) {
return pagedResult.getContent();
} else {
return new ArrayList<User>();
}
}
public User getUserById(Long id) throws UserNotFoundException {
Optional<User> user = userRepository.findById(id);
if (user.isPresent()) {
return user.get();
} else {
throw new UserNotFoundException("User does not exist for given id.");
}
}
public User createOrUpdateUser(User user2) throws UserNotFoundException {
Optional<User> user = userRepository.findById(user2.getId());
if (user.isPresent()) {
User user1 = user.get();
user1.setStatus(user2.getStatus());
user1.setFirstName(user2.getFirstName());
user1.setLastName(user2.getLastName());
return userRepository.save(user1);
} else {
return userRepository.save(user2);
}
}
public void deleteUserById(Long id) throws UserNotFoundException {
if (userRepository.findById(id).isPresent()) {
userRepository.deleteById(id);
} else {
throw new UserNotFoundException("User does not exist for given id.");
}
}
}
Test Pagination and Sorting
-
Start the Spring Boot application by using
mvn spring-boot run
command and use rest endpoint to get all users : http://localhost:8282/users . - Use rest
endpoint to get data with page size : http://localhost:8282/users?pageSize=1 .
- http://localhost:8282/users?pageSize=7&pageNo=2
- http://localhost:8282/users?pageSize=7&pageNo=2&sortBy=status
Download Source Code
The full source code for this article can be found on below.Download it here - Spring Boot Pagination Sorting Example