![]() |
VOOZH | about |
When working with large datasets, fetching all records at once can reduce performance and increase load on the application. Efficient data handling techniques are required to manage and process data smoothly.
Pagination is used to handle large datasets efficiently by breaking them into smaller parts. It helps improve performance and makes data retrieval more manageable.
Syntax:
Pageable pageable = PageRequest.of(pageNumber, pageSize);
Page<Entity> data = repository.findAll(pageable);
Sorting is used to organize data in a specific order, making it easier to read and analyze. It improves how data is presented and accessed in applications.
Syntax:
Sort sort = Sort.by("fieldName").ascending(); // or descending()
List<Entity> data = repository.findAll(sort);
Create a new Spring Boot project with the following details:
Add the following dependencies into the project.
Organize project into: Entity Repository Service Controller Helps maintain clean architecture.
spring.application.name=spring-sorting-pagination-demo
spring.datasource.url=jdbc:mysql://localhost:3306/product_db
spring.datasource.username=root
spring.datasource.password=mypassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
Product class with fields (id, name, price). @Entity, @Id. Product.java:
ProductRepository.java
Note: JpaRepository extends PagingAndSortingRepository, so you get pagination and sorting functionality without needing both.
findAll(Pageable pageable)ProductService.java:
Create REST API endpoint /products. Accept parameters:
ProductController.java:
@EnableSpringDataWebSupport helps in handling pagination response.Run the application. By default, it will start on port 8080.
To test the endpoint, use:
http://localhost:8080/products?page=0&size=5&sortBy=price&ascending=false
This fetches the first page of products, showing 5 records sorted by price in descending order.