Pagination

Author Avatar
Learn Here Fun Pedia
5 min read •

Pagination

Pagination means: Don't retrieve thousands or millions of records at once. Retrieve a limited subset.

Suppose your database has 100,000 employees. Instead of selecting all 100,000 rows into memory (which would crash your application), we want to fetch them in manageable chunks:

Page 0 → 20 records
Page 1 → 20 records
Page 2 → 20 records

In Spring Data JPA, this is incredibly easy. You just update your repository method to accept a Pageable object and return a Page:

Page<Employee> findAll(Pageable pageable);

When calling the method, you pass a PageRequest:

PageRequest.of(0, 20);

This means: Give me page index 0 (the first page), with a size of 20 records per page.

32. Sorting + Pagination

It is very rare that you want to paginate unsorted data. A very common real-world pattern is to combine sorting and pagination together.

Here is an example in Spring Data:

PageRequest.of(
    0,
    20,
    Sort.by("salary").descending()
);

Conceptually, this breaks down to:

  • Page: 0 (First page)
  • Size: 20 records
  • Sort: By salary in DESC order (highest paid first)

Why Database-Level Pagination is Critical

Database-level pagination is important because you DO NOT want this to happen:

Database
   ↓
(Returns 100,000 rows)
   ↓
Java Memory
   ↓
(Java discards 99,980 rows to take the first 20)

Instead, the database itself should perform the limiting and pagination. When you use Spring Data's Pageable, Hibernate translates this into highly efficient SQL constraints:

Database
   ↓
ORDER BY (Sorts data)
   ↓
LIMIT / OFFSET (Limits to 20 rows natively in the DB)
   ↓
(Returns exactly 20 rows)
   ↓
Java Application

Interactive Demo: Pagination and Sorting UI

To truly understand why we paginate, play with the interactive table below. It simulates a dataset of 50 records. Use the pagination controls at the bottom to jump between pages, and click the column headers to sort the data. Notice how the page size limits exactly how many DOM elements are rendered at once!

Idea: An interactive data table demonstrating pagination (Page 1, 2, 3...) and column sorting (ASC/DESC) to visualize how large datasets are broken into manageable chunks. Visual type: Interactive Paginated Data Table Data specification: - Data structure: Tabular dataset with ID (Number), Name (String), Department (String), and Salary (Number). - Initial values: Generate a mock array of 25 employee objects. Set default pagination size to 5 rows per page. - Mapping: Columns map to ID, Name, Department, and Salary. Sort icons appear next to headers when clicked. Pagination controls (Prev, Next, Page Numbers) appear below the table. User controls: Clickable table headers for sorting. Pagination buttons (Prev, 1, 2, 3, 4, 5, Next) to change the visible slice of data. Interactivity: - Click a header: Sorts that column ASC/DESC. - Click pagination: Updates the 5 rows currently visible in the table view (simulating LIMIT/OFFSET). Animation: Rows smoothly swap when sorting or changing pages.

T3 Interview Summary

If the interviewer asks: "Why do we use Pageable in Spring Data JPA instead of just returning a List?"

"Using Pageable ensures that pagination happens at the database level using SQL LIMIT and OFFSET (or their dialect equivalents). This prevents the application from loading thousands of records into Java heap memory at once, which would cause severe performance degradation and OutOfMemory errors. It allows us to retrieve and serve large datasets in small, manageable chunks."

Important Interview Questions (FAQs)

Q1: What is the difference between returning a Page and a Slice in Spring Data JPA?

A Page executes a secondary SQL COUNT query to determine the total number of records and total pages available. A Slice does not execute the count query; it only knows if there is a "next" slice of data available. Slice is faster for infinite-scroll UIs where you don't need to know the total page count.

Q2: Does PageRequest.of(0, 20) start at page 0 or page 1?

In Spring Data JPA, page indexing is zero-based. So PageRequest.of(0, 20) retrieves the very first page of results.

Q3: How does Hibernate handle pagination natively under the hood?

Hibernate translates the Pageable request into database-specific SQL. For example, in PostgreSQL or MySQL, it appends LIMIT 20 OFFSET 0. In older Oracle databases, it might use ROWNUM. Hibernate abstracts this dialect difference away from you.

Comments (0)