This content originally appeared on DEV Community and was authored by Sanju Shaw
Before beginning, let’s understand what pagination actually is.
Pagination simply means breaking a huge dataset into smaller chunks or pages. This is exactly what you see on e-commerce websites when products load page by page, or when you scroll through Google search results — you never get all the data at once.
It’s useful because:
- You save bandwidth.
- Backend responds faster
- UI becomes smoother.
- Database queries remain optimized
How to set-up pagination
Suppose we have an API like:
/api/books?query=adventure
Now we can easily configure the backend to limit the number of items returned.
Spring Data JPA already gives built-in support for pagination using Pageable.
We can also let the client decide how many results they want:
/api/books?query=adventure&page=0&size=20
-
page-> which page number(0-based index) -
size-> how many items per page
Let’s implement this properly.
Coding time
We are using Spring Boot + MySQL + Spring Data JPA.
1. Controller Layer
@RestController
@RequestMapping("/api/books")
public class BookController {
@Autowired
private BookService bookService;
@GetMapping
public Page<Book> getBooks(
@RequestParam(defaultValue = "adventure") String query,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
return bookService.getBooks(query, page, size);
}
}
- we use Spring’s
Pageclass -
page&sizehave default values. - Output automatically includes : totalElements, totalPages, current page number, size, and you actual data list.
2. Service Layer(Business Logic):
@Service
public class BookService {
@Autowired
private BookRepository bookRepository;
public Page<Book> getBooks(String query, int page, int size) {
Pageable pageable = PageRequest.of(page, size);
return bookRepository.findByTitleContainingIgnoreCase(query, pageable);
}
}
Here:
- `PageRequest.of(page, size) creates the pagination configuration.
- Repository method automatically handles pagination.
3. Repository Layer:
This is the beauty of Spring Data JPA – no SQL written manually.
It handles :
- LIMIT
- OFFSET
- Filtering
- Sorting All under the hood.
want to sort the results??
bash
/api/books?page=0&size=10&sort=price,desc
Change your controller parameter:
Final Result
If you call:
bash
GET /api/books?query=adventure&page=0&size=5
Response be like:
This is how pagination works smoothly in Spring Boot.
Follow me for more Java oriented and system design content. Thanks for reading!
This content originally appeared on DEV Community and was authored by Sanju Shaw


