Menu

Pagination, Sorting and Projections

Pagination, Sorting and Projections

Pagination

Loading every row is rarely needed. setFirstResult() sets how many rows to skip, and setMaxResults() sets the page size. Always add an order by, or pages can overlap or miss rows.

Page number 3 with a page size of 10 uses a first result of 20.

Projections

A projection selects only some fields instead of the full entity. This reduces the data read from the database. The results are plain objects, not managed entities, so they are not tracked for changes.

public record StudentSummary(Long id, String name) {}

List<Student> page = session
        .createSelectionQuery("from Student s order by s.name, s.id", Student.class)
        .setFirstResult(20)
        .setMaxResults(10)
        .getResultList();

List<StudentSummary> summaries = session
        .createSelectionQuery(
            "select new com.example.StudentSummary(s.id, s.name) from Student s",
            StudentSummary.class)
        .getResultList();

Code Explanation:

  • The first query skips 20 rows and returns the next 10, sorted by name and then by id to keep the order stable.
  • select new calls the constructor of StudentSummary with the selected values. The class name must be fully qualified.
  • Only id and name are read from the table.

Pagination combined with join fetch on a collection is unreliable. Hibernate then applies the limit in memory after loading all rows, and logs a warning when this happens.


Hibernate Tutorial

AP

Abhishek Pati



Learn via Video Course

Java Programming ( Telugu) Logo

Java Programming ( Telugu)

11 hrs



Get in Touch For Details