🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Learn everything about Spring Data JPA at https://www.javaguides.net/p/spring-data-jpa-tutorial.html
Let's first discuss pagination implementation using Spring Data JPA then we will move to sorting implementation.
Understand Spring Data JPA’s Pagination APIs
- Page findAll(Pageable pageable) – returns a Page of entities meeting the paging restriction provided in the Pageable object.
- Iterable findAll(Sort sort) – returns all entities sorted by the given options. No paging is applied here.
@NoRepositoryBean
public interface PagingAndSortingRepository < T, ID > extends CrudRepository < T, ID > {
/**
* Returns all entities sorted by the given options.
*
* @param sort
* @return all entities sorted by the given options
*/
Iterable < T > findAll(Sort sort);
/**
* Returns a {@link Page} of entities meeting the paging restriction provided in the {@code Pageable} object.
*
* @param pageable
* @return a page of entities
*/
Page < T > findAll(Pageable pageable);
}@NoRepositoryBean public interface JpaRepository < T, ID > extends PagingAndSortingRepository < T, ID > , QueryByExampleExecutor < T > { List < T > findAll(); List < T > findAll(Sort sort); List < T > findAllById(Iterable < ID > ids); <S extends T > List < S > saveAll(Iterable < S > entities); void flush(); <S extends T > S saveAndFlush(S entity); void deleteInBatch(Iterable < T > entities); void deleteAllInBatch(); T getOne(ID id); @Override < S extends T > List < S > findAll(Example < S > example); @Override < S extends T > List < S > findAll(Example < S > example, Sort sort); }
@Entity @Table(name = "employees") public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(name = "first_name") private String firstName; @Column(name = "last_name") private String lastName; @Column(name = "email") private String email;
int pageNumber = 1;
int pageSize = 5;
Pageable pageable = PageRequest.of(pageNumber, pageSize);
Page<Employee> page = employeeRepository.findAll(pageable);List<Employee> listEmployees = page.getContent();long totalItems = page.getTotalElements();
int totalPages = page.getTotalPages();Create EmployeeRepository
Let's create an EmployeeRepository interface which extends JpaRepository which intern extends the PagingAndSortingRepository interface so we can leverage pagination API:package net.javaguides.springboot.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import net.javaguides.springboot.model.Employee;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
}
package net.javaguides.springboot.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import net.javaguides.springboot.model.Employee;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
}Create EmployeeService interface
package net.javaguides.springboot.service;
import java.util.List;
import org.springframework.data.domain.Page;
import net.javaguides.springboot.model.Employee;
public interface EmployeeService {
Page < Employee > findPaginated(int pageNo, int pageSize);
}EmployeeServiceImpl Class
@Override
public Page<Employee> findPaginated(int pageNo, int pageSize) {
Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
return this.employeeRepository.findAll(pageable);
}2. Sorting Implementation
Understand Spring Data JPA’s Sorting API
@NoRepositoryBean
public interface PagingAndSortingRepository < T, ID > extends CrudRepository < T, ID > {
/**
* Returns all entities sorted by the given options.
*
* @param sort
* @return all entities sorted by the given options
*/
Iterable < T > findAll(Sort sort);
/**
* Returns a {@link Page} of entities meeting the paging restriction provided in the {@code Pageable} object.
*
* @param pageable
* @return a page of entities
*/
Page < T > findAll(Pageable pageable);
}Sort sort = Sort.by(“fieldName”).ascending();Sort sort = Sort.by("fieldName1").ascending().and(Sort.by("fieldName2").descending());Pageable pageable = PageRequest.of(pageNum - 1, pageSize, sort);Finally, we pass the pageable object to the findAll() method:this.employeeRepository.findAll(pageable);Create EmployeeRepository
Let's create an EmployeeRepository interface which extends JpaRepository which intern extends the PagingAndSortingRepository interface so we can leverage sorting API:package net.javaguides.springboot.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import net.javaguides.springboot.model.Employee;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
}
package net.javaguides.springboot.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import net.javaguides.springboot.model.Employee;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
}Let's see how to use EmployeeRepository in the service layer.
EmployeeService.java interface changes
Page<Employee> findPaginated(int pageNo, int pageSize, String sortField, String sortDirection);package net.javaguides.springboot.service;
import java.util.List;
import org.springframework.data.domain.Page;
import net.javaguides.springboot.model.Employee;
public interface EmployeeService {
Page < Employee > findPaginated(int pageNo, int pageSize, String sortField, String sortDirection);
}EmployeeServiceImpl.java class changes
@Override
public Page<Employee> findPaginated(int pageNo, int pageSize, String sortField, String sortDirection) {
Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name()) ? Sort.by(sortField).ascending() :
Sort.by(sortField).descending();
Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort);
return this.employeeRepository.findAll(pageable);
}Note that we are using the same method to perform both pagination and sorting operations.
Check out the complete example at Pagination and Sorting with Spring Boot, ThymeLeaf, Spring Data JPA, Hibernate, MySQL
3. Spring Data JPA interfaces
Check out the below diagram which shows the main interfaces of Spring Data JPA for your reference:
Video Tutorial
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business

Comments
Post a Comment
Leave Comment