Add Restrictions to the Criteria object in Hibernate

In this example we shall show you how to add restrictions to the Criteria object in Hibernate. In Hibernate, Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like “search” screens where there is a variable number of conditions to be placed upon the result set. The Session is a factory for Criteria. Criterion instances are usually obtained via the factory methods on Restrictions. We have set an example to insert to a database using Hibernate Criteria, as described below:

  • Employee class is the class whose objects will be inserted to the database.
  • In AddRestrictionsToTheCriteriaObjectInHibernate 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.
  • Use add(Criterion criterion) to add Restrictions to constrain the results to be retrieved.
  • Use methods of Restrictions to constraint the results. For example, eq(String propertyName, Object value) applies an “equal” constraint to the named property, like(String propertyName, Object value) applies a “like” constraint to the named property and isNotNull(String propertyName) applies an “is not null” constraint to the named property.
  • Use the list() API method of Criteria to get the results, after having applied the constraints.
  • 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 AddRestrictionsToTheCriteriaObjectInHibernate 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;
import org.hibernate.criterion.Restrictions;

public class AddRestrictionsToTheCriteriaObjectInHibernate {
	public static void main(String[] args) {
		SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
		Session session = sessionFactory.getCurrentSession();
		try {
			Employee employee = new Employee();
			employee.setTitle("QA Engineer");
			employee.setCreated(new Date());
			employee = new Employee();
			employee.setTitle("Project Manager");
			employee.setCreated(new Date());
			employee = new Employee();
			employee.setTitle("Junior Developer");
			employee.setCreated(new Date());
			employee = new Employee();
			employee.setTitle("Software Developer");
			employee.setCreated(new Date());
		catch (HibernateException e) {
		session = sessionFactory.getCurrentSession();

		try {
			Criteria criteria = session.createCriteria(Employee.class);
			criteria.add(Restrictions.eq("name", "helen"));
			criteria.add(Restrictions.like("surname", "%son%"));
			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() +
							" - " + employee.getSurname());
		catch (HibernateException e) {

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;



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

<!DOCTYPE hibernate-configuration PUBLIC

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



  <!-- 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" />



<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

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



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

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

<generator class="native"/>


  <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" />


Total Results:1
3 - Helen - Potson

This was an example of how to add restrictions to the Criteria object in Hibernate.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button