Pagination is a technique used to retrieve large datasets in smaller, manageable chunks instead of loading all records at once. In Spring Boot, pagination is commonly implemented using Spring Data JPA's Pageable and Page interfaces, which improve performance, reduce memory consumption, and enhance user experience.
Key Points: • Pagination retrieves only the required subset of records from the database. • Spring Data JPA provides built-in support through Pageable, PageRequest, and Page interfaces. • Pagination can be combined with sorting and filtering for efficient data retrieval.
Example: Consider an e-commerce application containing 1 million products. Instead of loading all products at once, the application retrieves 20 products per page, significantly improving performance and response time.
Repository Layer:
public interface ProductRepository
extends JpaRepository<Product, Long> {Page<Product> findAll(
Pageable pageable);
}Service Layer:
@Service
public class ProductService {
@Autowired
private ProductRepository repository;
public Page<Product> getProducts(int page,
int size) {
Pageable pageable =
PageRequest.of(
page,
size);return repository.findAll(
pageable);
}
}Controller Layer:
@RestController
@RequestMapping("/products")
public class ProductController {
@Autowired
private ProductService service;
@GetMapping
public Page<Product> getProducts(
@RequestParam(defaultValue = "0")int page,
@RequestParam(defaultValue = "10")
int size) {return service.getProducts(
page,
size);
}
}API Request:
GET /products?page=0&size=10
Response Contains:
• Current Page • Total Pages • Total Records • Page Size • List of Records
Pagination with Sorting:
Pageable pageable =
PageRequest.of(
page,
size,
Sort.by("name")
.ascending());This returns paginated and sorted data.
Common Page Methods:
• getContent() - Returns records in the current page.
• getTotalElements() - Total number of records.
• getTotalPages() - Total available pages.
• getNumber() - Current page number.
• hasNext() - Checks if another page exists.
Benefits:
• Improved application performance. • Reduced memory consumption. • Faster database queries. • Better user experience. • Efficient handling of large datasets.
Real-World Example:
In an employee management system:
• Total Employees: 100,000 • Records Per Page: 20
Instead of transferring all records, the application loads only the requested page, reducing network traffic and improving response times.
Interview Tip: A concise interview answer is: Pagination in Spring Boot is typically implemented using Spring Data JPA's Pageable and Page interfaces. A PageRequest object is created with the desired page number and size and passed to repository methods. Spring Data JPA automatically generates the required SQL queries and returns paginated results along with metadata such as total records and total pages.