In this tutorial, we are going to see a quick introduction of Hibernate Pagination. Pagination in Hibernate provides an ability to read huge data into smaller chunks.

Hibernate Pagination:

As part of this tutorial, we are going to create a simple item table having a bulk of data, and reading data into smaller chunks using pagination.

Technologies:

  • Java 8
  • Hibernate 5.2.12
  • MySQL
  • Maven

Project Structure:

Hibernate Pagination Example

Project Dependencies:

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>Hibernate_Pagination</groupId>
    <artifactId>Hibernate_Pagination</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- MySQL connector -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.5</version>
        </dependency>

        <!-- Hibernate 5.2.12 Final -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.12.Final</version>
        </dependency>
    </dependencies>
    <build>
        <sourceDirectory>src/main/java</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Hibernate configirations.

Hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/otp</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">1234</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <property name="hibernate.show_sql">true</property>
    <mapping class="com.onlinetutorialspoint.entity.Item" />
  </session-factory>
</hibernate-configuration>

Creating Item class representing the item table in the database.

Item.java
package com.onlinetutorialspoint.entity;

import javax.persistence.*;

@Entity
@Table(name="item")
public class Item {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    @Column(name="id")
    private int itemId;
    @Column(name="item_name",length=30)
    private String itemName;
    @Column(name="category",length=30)
    private String itemCategory;
    @Column(name="item_price")
    private double itemPrice;

    public Item() {
    }

    public Item(String itemName, String itemCategory, double itemPrice) {
        this.itemName = itemName;
        this.itemCategory = itemCategory;
        this.itemPrice = itemPrice;
    }

    public int getItemId() {
        return itemId;
    }

    public void setItemId(int itemId) {
        this.itemId = itemId;
    }

    public String getItemName() {
        return itemName;
    }

    public void setItemName(String itemName) {
        this.itemName = itemName;
    }

    public String getItemCategory() {
        return itemCategory;
    }

    public void setItemCategory(String itemCategory) {
        this.itemCategory = itemCategory;
    }

    public double getItemPrice() {
        return itemPrice;
    }

    public void setItemPrice(double itemPrice) {
        this.itemPrice = itemPrice;
    }

    @Override
    public String toString() {
        return "Item{" +
                "itemId=" + itemId +
                ", itemName='" + itemName + '\'' +
                ", itemCategory='" + itemCategory + '\'' +
                ", itemPrice=" + itemPrice +
                '}';
    }
}

Hibernate Utility class.

HibernateUtil.java
package com.onlinetutorialspoint.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtil {
  private static StandardServiceRegistry standardServiceRegistry;
  private static SessionFactory sessionFactory;

  static{
      if (sessionFactory == null) try {
      standardServiceRegistry = new StandardServiceRegistryBuilder()
          .configure()
          .build();
      MetadataSources metadataSources = new MetadataSources(standardServiceRegistry);
      Metadata metadata = metadataSources.getMetadataBuilder().build();
      sessionFactory = metadata.getSessionFactoryBuilder().build();
    } catch (Exception e) {
      e.printStackTrace();
      if (standardServiceRegistry != null) {
        StandardServiceRegistryBuilder.destroy(standardServiceRegistry);
      }
    }
  }
  public static SessionFactory getSessionFactory() {
    return sessionFactory;
  }
}

Inserting data into the table: Here I am going to insert 100 items into items table.

HibernatePagination.java
public static void insertItems(){
        Transaction transaction =  null;
        try(Session session = HibernateUtil.getSessionFactory().openSession() ) {
            transaction = session.beginTransaction();
            IntStream.range(0, 100).forEach(count -> {
                session.save(new Item("Item" + count, "Item" + count + "Desc", count));
            });
            transaction.commit();

        } catch (Exception e) {
            if(transaction != null && transaction.isActive())
                transaction.rollback();
            throw e;
        }
    }

Now we are ready to read the data from the item table by chunks.

Hibernate Pagination Example:

we can do the pagination in hibernate in different ways. Let’s see how we can do using HQL query.

Hibernate Pagination using HQL query:

Create Hibernate HQL query using session.createQuery() method. And set the FirstResult() and MaxResults() on query object to make the pagination.

HibernatePagination.java
private static void paginationUsingHQL() {
    try (Session session = HibernateUtil.getSessionFactory().openSession()) {
        Query query = session.createQuery("From Item");
        int pageSize = 10;
        //setting pagination limits
        query.setFirstResult(0);
        query.setMaxResults(pageSize);
        printItems(query.getResultList());
    }catch(Exception e){
        e.printStackTrace();
    }
}
private static void printItems(List<Item> itemsList) {
    itemsList.forEach(System.out::println);
}

Above example prints the results from 0 to 10 records like below. We can see the generated SQL query with a limit attribute.

Terminal
Hibernate: select item0_.id as id1_0_, item0_.category as category2_0_, item0_.item_name as item_nam3_0_, item0_.item_price as item_pri4_0_ from item item0_ limit ?
Item{itemId=1701, itemName='Item0', itemCategory='Item0Desc', itemPrice=0.0}
Item{itemId=1702, itemName='Item1', itemCategory='Item1Desc', itemPrice=1.0}
Item{itemId=1703, itemName='Item2', itemCategory='Item2Desc', itemPrice=2.0}
Item{itemId=1704, itemName='Item3', itemCategory='Item3Desc', itemPrice=3.0}
Item{itemId=1705, itemName='Item4', itemCategory='Item4Desc', itemPrice=4.0}
Item{itemId=1706, itemName='Item5', itemCategory='Item5Desc', itemPrice=5.0}
Item{itemId=1707, itemName='Item6', itemCategory='Item6Desc', itemPrice=6.0}
Item{itemId=1708, itemName='Item7', itemCategory='Item7Desc', itemPrice=7.0}
Item{itemId=1709, itemName='Item8', itemCategory='Item8Desc', itemPrice=8.0}
Item{itemId=1710, itemName='Item9', itemCategory='Item9Desc', itemPrice=9.0}

Hibernate Pagination using Criteria query:

Hibernate criteria to make the pagination.

HibernatePagination.java
private static void paginationUsingCriteria() {
    try (Session session = HibernateUtil.getSessionFactory().openSession()) {
        int pageSize = 15;

        CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
        CriteriaQuery<Item> criteriaQuery = criteriaBuilder.createQuery(Item.class);
        Root<Item> root = criteriaQuery.from(Item.class);

        CriteriaQuery<Item> selectQuery = criteriaQuery.select(root);
        TypedQuery<Item> typedQuery = session.createQuery(selectQuery);

        // setting pagination limits
        typedQuery.setFirstResult(10);
        typedQuery.setMaxResults(pageSize);

        printItems(typedQuery.getResultList());

    }catch(Exception e){
        e.printStackTrace();
    }
}

Here we will see the results from 10 to 24 records.

Terminal
Hibernate: select item0_.id as id1_0_, item0_.category as category2_0_, item0_.item_name as item_nam3_0_, item0_.item_price as item_pri4_0_ from item item0_ limit ?, ?
Item{itemId=1711, itemName='Item10', itemCategory='Item10Desc', itemPrice=10.0}
Item{itemId=1712, itemName='Item11', itemCategory='Item11Desc', itemPrice=11.0}
Item{itemId=1713, itemName='Item12', itemCategory='Item12Desc', itemPrice=12.0}
Item{itemId=1714, itemName='Item13', itemCategory='Item13Desc', itemPrice=13.0}
Item{itemId=1715, itemName='Item14', itemCategory='Item14Desc', itemPrice=14.0}
Item{itemId=1716, itemName='Item15', itemCategory='Item15Desc', itemPrice=15.0}
Item{itemId=1717, itemName='Item16', itemCategory='Item16Desc', itemPrice=16.0}
Item{itemId=1718, itemName='Item17', itemCategory='Item17Desc', itemPrice=17.0}
Item{itemId=1719, itemName='Item18', itemCategory='Item18Desc', itemPrice=18.0}
Item{itemId=1720, itemName='Item19', itemCategory='Item19Desc', itemPrice=19.0}
Item{itemId=1721, itemName='Item20', itemCategory='Item20Desc', itemPrice=20.0}
Item{itemId=1722, itemName='Item21', itemCategory='Item21Desc', itemPrice=21.0}
Item{itemId=1723, itemName='Item22', itemCategory='Item22Desc', itemPrice=22.0}
Item{itemId=1724, itemName='Item23', itemCategory='Item23Desc', itemPrice=23.0}
Item{itemId=1725, itemName='Item24', itemCategory='Item24Desc', itemPrice=24.0}

Reading entire data with 10 records per pagination.

HibernatePagination.java
private static void readEntireDataByPagination() {
    try (Session session = HibernateUtil.getSessionFactory().openSession()) {
        int pageNumber = 1;
        int pageSize = 10;

        CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
        CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class);

        countQuery.select(criteriaBuilder.count(countQuery.from(Item.class)));
        Long count = session.createQuery(countQuery).getSingleResult();

        CriteriaQuery<Item> criteriaQuery = criteriaBuilder.createQuery(Item.class);
        Root<Item> root = criteriaQuery.from(Item.class);
        CriteriaQuery<Item> selectQuery = criteriaQuery.select(root);

        TypedQuery<Item> typedQuery = session.createQuery(selectQuery);
        while (pageNumber < count.intValue()) {
            System.out.println("Page: " +(pageNumber/pageSize));
            typedQuery.setFirstResult(pageNumber - 1);
            typedQuery.setMaxResults(pageSize);

            printItems(typedQuery.getResultList());
            pageNumber += pageSize;

            System.out.println("==========================");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Now we can see the pagination results by 10 records per page.

Terminal
Hibernate: select count(item0_.id) as col_0_0_ from item item0_
Page: 0
Hibernate: select item0_.id as id1_0_, item0_.category as category2_0_, item0_.item_name as item_nam3_0_, item0_.item_price as item_pri4_0_ from item item0_ limit ?
Item{itemId=1701, itemName='Item0', itemCategory='Item0Desc', itemPrice=0.0}
Item{itemId=1702, itemName='Item1', itemCategory='Item1Desc', itemPrice=1.0}
Item{itemId=1703, itemName='Item2', itemCategory='Item2Desc', itemPrice=2.0}
Item{itemId=1704, itemName='Item3', itemCategory='Item3Desc', itemPrice=3.0}
Item{itemId=1705, itemName='Item4', itemCategory='Item4Desc', itemPrice=4.0}
Item{itemId=1706, itemName='Item5', itemCategory='Item5Desc', itemPrice=5.0}
Item{itemId=1707, itemName='Item6', itemCategory='Item6Desc', itemPrice=6.0}
Item{itemId=1708, itemName='Item7', itemCategory='Item7Desc', itemPrice=7.0}
Item{itemId=1709, itemName='Item8', itemCategory='Item8Desc', itemPrice=8.0}
Item{itemId=1710, itemName='Item9', itemCategory='Item9Desc', itemPrice=9.0}
==========================
Page: 1
Hibernate: select item0_.id as id1_0_, item0_.category as category2_0_, item0_.item_name as item_nam3_0_, item0_.item_price as item_pri4_0_ from item item0_ limit ?, ?
Item{itemId=1711, itemName='Item10', itemCategory='Item10Desc', itemPrice=10.0}
Item{itemId=1712, itemName='Item11', itemCategory='Item11Desc', itemPrice=11.0}
Item{itemId=1713, itemName='Item12', itemCategory='Item12Desc', itemPrice=12.0}
Item{itemId=1714, itemName='Item13', itemCategory='Item13Desc', itemPrice=13.0}
Item{itemId=1715, itemName='Item14', itemCategory='Item14Desc', itemPrice=14.0}
Item{itemId=1716, itemName='Item15', itemCategory='Item15Desc', itemPrice=15.0}
Item{itemId=1717, itemName='Item16', itemCategory='Item16Desc', itemPrice=16.0}
Item{itemId=1718, itemName='Item17', itemCategory='Item17Desc', itemPrice=17.0}
Item{itemId=1719, itemName='Item18', itemCategory='Item18Desc', itemPrice=18.0}
Item{itemId=1720, itemName='Item19', itemCategory='Item19Desc', itemPrice=19.0}
==========================
Page: 2
Hibernate: select item0_.id as id1_0_, item0_.category as category2_0_, item0_.item_name as item_nam3_0_, item0_.item_price as item_pri4_0_ from item item0_ limit ?, ?
Item{itemId=1721, itemName='Item20', itemCategory='Item20Desc', itemPrice=20.0}
Item{itemId=1722, itemName='Item21', itemCategory='Item21Desc', itemPrice=21.0}
Item{itemId=1723, itemName='Item22', itemCategory='Item22Desc', itemPrice=22.0}
......
......

 

References:

Happy Learning 🙂

Download Example

About the Author:

Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment