✅ What is Pagination?

Pagination is a technique to split large sets of data into smaller, manageable chunks (pages), improving performance and user experience—especially in APIs and UI tables.


🔧 Why Use Pagination?

  • 🐢 Prevents performance issues with large data sets.
  • Improves API response time.
  • 📱 Better UX in frontend (infinite scroll, paged tables, etc.).

🔢 Example: Pagination in Spring Boot (Using Spring Data JPA)

@GetMapping("/products")
public Page<Product> getProducts(@RequestParam(defaultValue = "0") int page,
                                 @RequestParam(defaultValue = "10") int size) {
    Pageable pageable = PageRequest.of(page, size);
    return productRepository.findAll(pageable);
}

💡 Output JSON:

{
  "content": [ /* list of products */ ],
  "totalPages": 5,
  "totalElements": 100,
  "size": 10,
  "number": 0
}

📦 Repository Interface

public interface ProductRepository extends JpaRepository<Product, Long> {
    Page<Product> findAll(Pageable pageable);
}

🧠 Key Terms

Term Meaning
Page Full page of results with metadata
Pageable Interface for pagination info
PageRequest.of(p, s) Creates a Pageable for page p of size s

🚀 Frontend-Friendly Params

Param Use
page=0 First page (0-based index)
size=10 Number of items per page
sort=name,desc Sort by name in descending order

✅ Bonus: Custom Query with Pagination

Page<Product> findByCategory(String category, Pageable pageable);
Back to blog

Leave a comment