Byron Kiourtzoglou

About Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

Pagination in Hibernate with Criteria API

This is an example of how to use pagination in Hibernate using the Criteria API. A typical way to create pagination over the results of a database is to define the number of rows per page and the number of pages. In order to use the pagination in Hibernate with Criteria API we have set the example below:

  • Employee class is the class whose objects will be inserted to the database.
  • In PaginationInHibernateWithCriteriaAPI we use the Hibernate API to make the interface with the database.
  • We create a new Configuration, that allows the application to specify properties and mapping documents to be used when creating a SessionFactory. Usually an application will create a single Configuration, build a single instance of SessionFactory and then instantiate Sessions in threads servicing client requests. Using configure() API method we use the mappings and properties specified in an application resource named hibernate.cfg.xml.  Then, with buildSessionFactory() we instantiate a new SessionFactory, using the properties and mappings in this configuration.
  • Use the getCurrentSession() API method to obtain the current session.
  • Use the beginTransaction() API method to begin a unit of work and return the associated Transaction object. If a new underlying transaction is required, begin the transaction. Otherwise continue the new work in the context of the existing underlying transaction.
  • Create new Employee objects and use save(Object object) API method of Session to persist the given transient instances to the database.
  • Use getTransaction() API method of Session and commit() API method of Transaction to commit the Transaction.
  • Use the beginTransaction() API method again. Now create a new Criteria, using the createCriteria(Class persistentClass) API method of Session for the given Employee class.
  • Define the number of pages and the number of rows per page.
  • Use setFirstResult(int firstResult) API method of Criteria to set the first result per page.
  • Use maxResults(int maxResults) API method of Criteria to set the max results of each page.
  • Use the list() API method of Criteria to get the results.
  • Use again getTransaction() API method of Session and commit() API method of Transaction to commit the Transaction.

In the code snippets that follow, you can see the Employee class and the PaginationInHibernateWithCriteriaAPI Class that applies all above steps. You can also take a look at the hibernate.cfg.xml file, that holds all configuration for Hibernate, such as JDBC connection settings, and employee.hbm.xml file that holds the mapping configuration between the Employee class and the Employee table. 

package com.javacodegeeks.snippets.enterprise;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class PaginationInHibernateWithCriteriaAPI {
	
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		
		SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
		
		Session session = sessionFactory.getCurrentSession();
		
		try {
			session.beginTransaction();
			
			for (int i = 0; i < 100; i++) {
				Employee employee = new Employee();
				employee.setName("employe_"+i);
				employee.setSurname("surname_"+i);
				employee.setTitle("Engineer_"+i);
				employee.setCreated(new Date());
				session.save(employee);
			}
			
			session.getTransaction().commit();
		}
		catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		
		session = sessionFactory.getCurrentSession();
		
		int pageNumber = 2;
		int pageSize = 10;
		
		try {
			session.beginTransaction();
			
			Criteria criteria = session.createCriteria(Employee.class);
			criteria.setFirstResult((pageNumber - 1) * pageSize);
			criteria.setMaxResults(pageSize);
			
			List<Employee> employees = (List<Employee>) criteria.list();
			if (employees!=null) {
				System.out.println("Total Results:" + employees.size());
				for (Employee employee : employees) {
					System.out.println(employee.getId() + " - " + employee.getName());
				}
			}
			
			session.getTransaction().commit();
		}
		catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		
	}

}
package com.javacodegeeks.snippets.enterprise;

import java.util.Date;

public class Employee {
	
	private Long id;
    private String name;
    private String surname;
    private String title;
    private Date created;
    
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public String getSurname() {
		return surname;
	}
	public void setSurname(String surname) {
		this.surname = surname;
	}
	
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	
	public Date getCreated() {
		return created;
	}
	public void setCreated(Date created) {
		this.created = created;
	}

}

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

  "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

  
<hibernate-configuration>
    <session-factory>

  <!-- JDBC connection settings -->

  <property name="connection.driver_class">com.mysql.jdbc.Driver</property>

  <property name="connection.url">jdbc:mysql://localhost/companydb</property>

  <property name="connection.username">jcg</property>

  <property name="connection.password">jcg</property>

  

  <!-- JDBC connection pool, use Hibernate internal connection pool -->

  <property name="connection.pool_size">5</property>


  <!-- Defines the SQL dialect used in Hiberante's application -->

  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>


  <!-- Enable Hibernate's automatic session context management -->

  <property name="current_session_context_class">thread</property>


  <!-- Disable the second-level cache  -->

  <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>


  <!-- Display and format all executed SQL to stdout -->

  <property name="show_sql">true</property>

  <property name="format_sql">true</property>


  <!-- Drop and re-create the database schema on startup -->

  <property name="hbm2ddl.auto">update</property>

  

  <!-- Mapping to hibernate mapping files -->

  <mapping resource="Employee.hbm.xml" />

  
    </session-factory>
    
</hibernate-configuration>

Employee.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

  
<hibernate-mapping>

    <class name="com.javacodegeeks.snippets.enterprise.Employee" table="employee">

  <id name="id" column="id">


<generator class="native"/>

  </id>

  <property name="name" not-null="true" length="50" />

  <property name="surname" not-null="true" length="50" />

  <property name="title" length="50" />

  <property name="created" type="timestamp" />
    </class>
    
</hibernate-mapping>
CREATE TABLE `companydb`.`employee` (
  `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NOT NULL,
  `surname` VARCHAR(45) NOT NULL,
  `title` VARCHAR(45) NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
);

Output:

Total Results:10
11 - employe_10
12 - employe_11
13 - employe_12
14 - employe_13
15 - employe_14
16 - employe_15
17 - employe_16
18 - employe_17
19 - employe_18
20 - employe_19

 
This was an example of how to use pagination in Hibernate using the Criteria API.

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books