JPA Buddy
announcement - icon

JPA is huge! It covers nearly every aspect of communication between relational databases and the Java application and is deeply integrated into all major frameworks.

If you're using IntelliJ, JPA Buddy is super helpful. The plugin gently guides you through the subtleties of the most popular JPA implementations, visually reminds you of JPA features, generates code that follows best practices, and integrates intelligent inspections to improve your existing persistence code.

More concretely, it provides powerful tooling to generate Spring Data JPA repositories and methods, Flyway Versioned Migrations, Liquibase Differential Changelogs, DDL and SQL statements, DTO objects, and MapStruct interfaces.

Oh, and it actually generates JPA entities from an existing database and gradually update the data model as the database evolves! Yeah.

>> Become a lot more productive with JPA Buddy

Persistence top

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:


1. Overview

This article is a quick introduction to Pagination in Hibernate. We will look at the standard HQL as well as the ScrollableResults API, and finally, at pagination with Hibernate Criteria.

Further reading:

Bootstrapping Hibernate 5 with Spring

A quick and practical guide to integrating Hibernate 5 with Spring.

Hibernate Inheritance Mapping

A practical guide to understanding different inheritance mapping strategies with JPA / Hibernate.

Show Hibernate/JPA SQL Statements from Spring Boot

Learn how you can configure logging of the generated SQL statements in your Spring Boot application.

2. Pagination With HQL and setFirstResult, setMaxResults API

The simplest and most common way to do pagination in Hibernate is using HQL:

Session session = sessionFactory.openSession();
Query query = sess.createQuery("From Foo");
List<Foo> fooList = fooList = query.list();

This example is using a basic Foo entity and is very much similar to the JPA with JQL implementation – the only difference being the query language.

If we turn on logging for Hibernate, we'll see the following SQL being run:

    select as id1_1_, as name2_1_ 
        Foo foo0_ limit ?

2.1. The Total Count and the Last Page

A pagination solution is not complete without knowing the total number of entities:

String countQ = "Select count ( from Foo f";
Query countQuery = session.createQuery(countQ);
Long countResults = (Long) countQuery.uniqueResult();

And lastly, from the total number and a given page size, we can calculate the last page:

int pageSize = 10;
int lastPageNumber = (int) (Math.ceil(countResults / pageSize));

At this point we can look at a complete example for pagination, where we are calculating the last page and then retrieving it:

public void givenEntitiesExist_whenRetrievingLastPage_thenCorrectSize() {
    int pageSize = 10;
    String countQ = "Select count ( from Foo f";
    Query countQuery = session.createQuery(countQ);
    Long countResults = (Long) countQuery.uniqueResult();
    int lastPageNumber = (int) (Math.ceil(countResults / pageSize));

    Query selectQuery = session.createQuery("From Foo");
    selectQuery.setFirstResult((lastPageNumber - 1) * pageSize);
    List<Foo> lastPage = selectQuery.list();

    assertThat(lastPage, hasSize(lessThan(pageSize + 1)));

3. Pagination With Hibernate Using HQL and the ScrollableResults API

Using ScrollableResults to implement pagination has the potential to reduce database calls. This approach streams the result set as the program scrolls through it, therefore eliminating the need to repeat the query to fill each page:

String hql = "FROM Foo f order by";
Query query = session.createQuery(hql);
int pageSize = 10;

ScrollableResults resultScroll = query.scroll(ScrollMode.FORWARD_ONLY);
List<Foo> fooPage = Lists.newArrayList();
int i = 0;
while (pageSize > i++) {
    fooPage.add((Foo) resultScroll.get(0));
    if (!

This method is not only time-efficient (only one database call), but it allows the user to get access to the total count of the result set without an additional query:

int totalResults = resultScroll.getRowNumber() + 1;

On the other hand, keep in mind that, although scrolling is quite efficient, a large window may take up a decent amount of memory.

4. Pagination With Hibernate Using the Criteria API

Finally, let's look at a more flexible solution – using criteria:

Criteria criteria = session.createCriteria(Foo.class);
List<Foo> firstPage = criteria.list();

Hibernate Criteria query API makes it very simple to also get the total count – by using a Projection object:

Criteria criteriaCount = session.createCriteria(Foo.class);
Long count = (Long) criteriaCount.uniqueResult();

As you can see, using this API will result in minimally more verbose code than plain HQL, but the API is fully type safe and a lot more flexible.

5. Conclusion

This article is a quick introduction to the various ways of doing pagination in Hibernate.

The implementation of this Spring JPA Tutorial can be found in the GitHub project – this is an Eclipse based project, so it should be easy to import and run as it is.

Persistence bottom
Get started with Spring Data JPA through the reference Learn Spring Data JPA course: >> CHECK OUT THE COURSE
Persistence footer banner
Comments are closed on this article!