Hibernate - Pagination

Last Updated : 20 Apr, 2026

Pagination in HQL is a technique used to fetch a limited number of records from a large dataset. It divides results into smaller pages instead of loading all data at once. It uses setFirstResult() and setMaxResults() to improve performance and efficiency.

  • Uses setFirstResult() to define starting index (zero-based)
  • Uses setMaxResults() to limit number of records
  • Helps fetch data page by page
  • Improves application performance
  • Reduces memory and server load

Pagination Process

1. Create HQL Query

  • Write query to fetch data
  • Example: FROM Employee
Java
String hql = "FROM User";
Query query = session.createQuery(hql);

2. Set Starting Index

  • Use setFirstResult()
  • Defines where data retrieval begins
Java
int firstResult = 20;
query.setFirstResult(firstResult);

3. Set Maximum Results

  • Use setMaxResults()
  • Defines how many records to fetch
Java
int maxResults = 10;
query.setMaxResults(maxResults);

4. Execute Query

  • Use list() or getResultList()
  • Retrieves paginated data
Java
List<User> users = query.list();

5. Display Results

  • Show data on UI (table/list)
  • Add navigation (Next/Previous buttons)

Example

If the Employee table has thousands of records, loading all at once is slow. Pagination helps fetch only a limited number of records per page. This improves performance and makes data display faster and efficient.

Java
// Calculate pagination parameters
int pageNumber = 1;
int pageSize = 10;
int firstResult = (pageNumber - 1) * pageSize;

// Create a HQL query to retrieve employees
String hql = "FROM Employee";
Query query = session.createQuery(hql);

// Set pagination parameters
query.setFirstResult(firstResult);
query.setMaxResults(pageSize);

// Retrieve employees from the database
List<Employee> employees = query.list();

// Display employees on the current page
for (Employee employee : employees) {
    System.out.println(employee.getName() + " - " + employee.getSalary());
}

Explanation: Calculate page number and size, then create an HQL query for Employee data. Use setFirstResult() and setMaxResults() to apply pagination. Fetch and display only limited records per page for better performance.

Pagination Benefits

  • Faster page loading times: By limiting the amount of data that is loaded at once, pagination can improve the performance of web pages, reducing the load time and improving the user experience.
  • Improved user experience: By breaking up the data into smaller pages, users can more easily navigate through the data and find the information they need.
  • Reduced server load: By limiting the amount of data that is loaded at once, pagination can reduce the strain on the server and improve scalability.
Comment