Criteria in Hibernate

We have learned about HQL in previous articles, Now lets talk about Hibernate Criteria Query Language (HCQL) in this article.

Let us understand Hibernate Criteria Query Language (HCQL)

What is HCQL

It’s a Criteria based query language mainly used to fetch the records based on specific search criteria.

It supports complete object oriented approach for querying and retrieving the result from database based on search criteria.

HCQL can not be used to perform DDL operations like Insert,Update and Delete.

It can be used only for retrieving the records based on search conditions.

Criteria queries should be preferred when we have many optional search condtions.

org.hibernate.Criteria interface has provided several methods to add search conditions.

Most commonly used methods in Criteria are


public Criteria add(Criterion c):
This method is used to add restrictions on the search results.

public Criteria addOrder(Order o)
This method is used to define the ordering of result like ascending or descending.

public Criteria setFirstResult(int firstResult)

public Criteria setMaxResult(int totalResult)

These 2 methods are used to achieve pagination by specifying first and maximum records to be retrieved.

Example: If there are 50 records in database and if we are defining the pagination with 25 records per page
FirstResult – 1 and MaxResult – 25 and then FirstResult-26 and MaxResult -25

public List list()
This method returns the list of object on which we are searching.

public Criteria setProjection(Projection projection)
This method is used to set the projection to retrieve only specific columns in the result.

Possible restriction used in HCQL are

lt(less than)
le(less than or equal)
gt(greater than)
ge(greater than or equal)
eq(equal)
ne(not equal)
between
like

Lets consider Employee class and perform various Criteria search operations.

Step 1

Create hibernate project

Please refer Hibernate setup in eclipse article on how to do it.

Project Structure


HibernateCriteriaProjStru

Step 2

Update pom.xml with MYSQL and Hibernate depenedencies

  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4.  
  5.   <modelVersion>4.0.0</modelVersion>
  6.  
  7.   <groupId>HibernateCriteria</groupId>
  8.   <artifactId>HibernateCriteria</artifactId>
  9.   <version>0.0.1-SNAPSHOT</version>
  10.   <packaging>jar</packaging>
  11.  
  12.   <name>HibernateCriteria</name>
  13.   <url>http://maven.apache.org</url>
  14.  
  15.   <properties>
  16.     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  17.   </properties>
  18.  
  19.   <dependencies>
  20.     <dependency>
  21.       <groupId>junit</groupId>
  22.       <artifactId>junit</artifactId>
  23.       <version>3.8.1</version>
  24.       <scope>test</scope>
  25.     </dependency>
  26.      <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
  27.         <dependency>
  28.             <groupId>org.hibernate</groupId>
  29.             <artifactId>hibernate-core</artifactId>
  30.             <version>5.2.6.Final</version>
  31.         </dependency>
  32.         <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
  33.         <dependency>
  34.             <groupId>mysql</groupId>
  35.             <artifactId>mysql-connector-java</artifactId>
  36.             <version>6.0.5</version>
  37.         </dependency>
  38.   </dependencies>
  39. </project>
<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>HibernateCriteria</groupId>
  <artifactId>HibernateCriteria</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>HibernateCriteria</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
     <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.2.6.Final</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>6.0.5</version>
		</dependency>
  </dependencies>
</project>

Step 3

Create Employee class

  1. package com.kb.model;
  2.  
  3. import javax.persistence.Column;
  4. import javax.persistence.Entity;
  5. import javax.persistence.GeneratedValue;
  6. import javax.persistence.GenerationType;
  7. import javax.persistence.Id;
  8. import javax.persistence.Table;
  9.  
  10. @Entity
  11. @Table(name="Employee")
  12. public class Employee {
  13.  
  14.     @Id
  15.     @GeneratedValue(strategy = GenerationType.SEQUENCE)
  16.     @Column(name = "Employee_Id")
  17.     private int employeeId;
  18.    
  19.     @Column(name = "FirstName")
  20.     private String firstName;
  21.    
  22.     @Column(name = "LastName")
  23.     private String lastName;
  24.    
  25.     @Column(name = "Age")
  26.     private int age;
  27.    
  28.     @Column(name = "Education")
  29.     private String education;
  30.    
  31.     @Column(name = "Salary")
  32.     private int salary;
  33.    
  34.     public int getEmployeeId() {
  35.         return employeeId;
  36.     }
  37.     public void setEmployeeId(int employeeId) {
  38.         this.employeeId = employeeId;
  39.     }
  40.     public String getFirstName() {
  41.         return firstName;
  42.     }
  43.     public void setFirstName(String firstName) {
  44.         this.firstName = firstName;
  45.     }
  46.     public String getLastName() {
  47.         return lastName;
  48.     }
  49.     public void setLastName(String lastName) {
  50.         this.lastName = lastName;
  51.     }
  52.     public int getAge() {
  53.         return age;
  54.     }
  55.     public void setAge(int age) {
  56.         this.age = age;
  57.     }
  58.     public String getEducation() {
  59.         return education;
  60.     }
  61.     public void setEducation(String education) {
  62.         this.education = education;
  63.     }
  64.     public int getSalary() {
  65.         return salary;
  66.     }
  67.     public void setSalary(int salary) {
  68.         this.salary = salary;
  69.     }
  70. }
package com.kb.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="Employee")
public class Employee {

	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE)
	@Column(name = "Employee_Id")
	private int employeeId;
	
	@Column(name = "FirstName")
	private String firstName;
	
	@Column(name = "LastName")
	private String lastName;
	
	@Column(name = "Age")
	private int age;
	
	@Column(name = "Education")
	private String education;
	
	@Column(name = "Salary")
	private int salary;
	
	public int getEmployeeId() {
		return employeeId;
	}
	public void setEmployeeId(int employeeId) {
		this.employeeId = employeeId;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getEducation() {
		return education;
	}
	public void setEducation(String education) {
		this.education = education;
	}
	public int getSalary() {
		return salary;
	}
	public void setSalary(int salary) {
		this.salary = salary;
	}
}

We have specified Primary key as employeeId and generator class as “sequence” for automatic primary key generation.

Step 4

Create hibernate.cfg.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3.        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4.        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  5.  
  6. <hibernate-configuration>
  7.  
  8.     <session-factory>
  9.  
  10.         <!-- Database connection properties -->
  11.         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  12.         <property name="connection.url">jdbc:mysql://localhost/javainsimpleway</property>
  13.         <property name="connection.username">root</property>
  14.         <property name="connection.password">root</property>
  15.  
  16.         <!-- JDBC connection pool (using the built-in) -->
  17.         <property name="connection.pool_size">100</property>
  18.  
  19.         <!-- SQL dialect -->
  20.         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  21.  
  22.         <!-- Disable the second-level cache -->
  23.         <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
  24.  
  25.         <!-- Echo all executed SQL to stdout -->
  26.         <property name="show_sql">true</property>
  27.  
  28.         <!-- Format the generated Sql -->
  29.         <property name="format_sql">true</property>
  30.  
  31.         <!-- Dont Drop and re-create the database schema on startup,Just update
  32.             it -->
  33.         <property name="hbm2ddl.auto">update</property>
  34.  
  35.         <mapping class="com.kb.model.Employee" />
  36.  
  37.     </session-factory>
  38.  
  39. </hibernate-configuration>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
       "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
       "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

	<session-factory>

		<!-- Database connection properties -->
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost/javainsimpleway</property>
		<property name="connection.username">root</property>
		<property name="connection.password">root</property>

		<!-- JDBC connection pool (using the built-in) -->
		<property name="connection.pool_size">100</property>

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

		<!-- Disable the second-level cache -->
		<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

		<!-- Echo all executed SQL to stdout -->
		<property name="show_sql">true</property>

		<!-- Format the generated Sql -->
		<property name="format_sql">true</property>

		<!-- Dont Drop and re-create the database schema on startup,Just update 
			it -->
		<property name="hbm2ddl.auto">update</property>

		<mapping class="com.kb.model.Employee" />

	</session-factory>

</hibernate-configuration>

Step 5

Create Hibernate util class

  1. package com.kb.util;
  2.  
  3. import org.hibernate.SessionFactory;
  4. import org.hibernate.cfg.Configuration;
  5.  
  6. public class HibernateUtil {
  7.     private static final SessionFactory sessionFactory = buildSessionFactory();
  8.  
  9.     private static SessionFactory buildSessionFactory() {
  10.         try {
  11.             // Create the SessionFactory from hibernate.cfg.xml
  12.             return new Configuration().configure().buildSessionFactory();
  13.         } catch (Throwable ex) {
  14.             // Make sure you log the exception to track it
  15.             System.err.println("SessionFactory creation failed." + ex);
  16.             throw new ExceptionInInitializerError(ex);
  17.         }
  18.     }
  19.  
  20.     public static SessionFactory getSessionFactory() {
  21.         return sessionFactory;
  22.     }
  23.    
  24.     public static void shutdown() {
  25.         // Optional but can be used to Close caches and connection pools
  26.         getSessionFactory().close();
  27.     }
  28.  
  29. }
package com.kb.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception to track it
            System.err.println("SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
    public static void shutdown() {
    	// Optional but can be used to Close caches and connection pools
    	getSessionFactory().close();
    }

}

Step 6

Create PopulateData.java file to Populate Employee Table with initial data

  1. package com.kb.db;
  2.  
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5. import org.hibernate.Transaction;
  6.  
  7. import com.kb.model.Employee;
  8. import com.kb.util.HibernateUtil;
  9.  
  10. public class PopulateData {
  11. public static void main(String[] args) {
  12.  
  13.     // Get session factory using Hibernate Util class
  14.     SessionFactory sf = HibernateUtil.getSessionFactory();
  15.     // Get session from Sesson factory
  16.     Session session = sf.openSession();
  17.  
  18.     // Begin transaction
  19.     Transaction t = session.beginTransaction();
  20.    
  21.     //Create Employee  data
  22.     Employee employee1 = new Employee();
  23.     employee1.setFirstName("John");
  24.     employee1.setLastName("KC");
  25.     employee1.setAge(28);
  26.     employee1.setEducation("PG");
  27.     employee1.setSalary(25000);
  28.    
  29.     Employee employee2 = new Employee();
  30.     employee2.setFirstName("Jacob");
  31.     employee2.setLastName("JC");
  32.     employee2.setAge(30);
  33.     employee2.setEducation("PG");
  34.     employee2.setSalary(30000);
  35.    
  36.     Employee employee3 = new Employee();
  37.     employee3.setFirstName("Martin");
  38.     employee3.setLastName("A");
  39.     employee3.setAge(24);
  40.     employee3.setEducation("UG");
  41.     employee3.setSalary(20000);
  42.    
  43.     Employee employee4 = new Employee();
  44.     employee4.setFirstName("Peter");
  45.     employee4.setLastName("M");
  46.     employee4.setAge(25);
  47.     employee4.setEducation("UG");
  48.     employee4.setSalary(22000);
  49.    
  50.     Employee employee5 = new Employee();
  51.     employee5.setFirstName("Roshan");
  52.     employee5.setLastName("B");
  53.     employee5.setAge(29);
  54.     employee5.setEducation("PG");
  55.     employee5.setSalary(45000);
  56.    
  57.    
  58.     session.save(employee1);
  59.     session.save(employee2);
  60.     session.save(employee3);
  61.     session.save(employee4);
  62.     session.save(employee5);
  63.  
  64.     // Commit the transaction and close the session
  65.     t.commit();
  66.    
  67.     session.close();
  68.     System.out.println("successfully persisted Employee details");
  69.  
  70.    }
  71.  
  72. }
package com.kb.db;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.kb.model.Employee;
import com.kb.util.HibernateUtil;

public class PopulateData {
public static void main(String[] args) {

	// Get session factory using Hibernate Util class
	SessionFactory sf = HibernateUtil.getSessionFactory();
	// Get session from Sesson factory
	Session session = sf.openSession();

	// Begin transaction
	Transaction t = session.beginTransaction();
	
	//Create Employee  data
	Employee employee1 = new Employee();
	employee1.setFirstName("John");
	employee1.setLastName("KC");
	employee1.setAge(28);
	employee1.setEducation("PG");
	employee1.setSalary(25000);
	
	Employee employee2 = new Employee();
	employee2.setFirstName("Jacob");
	employee2.setLastName("JC");
	employee2.setAge(30);
	employee2.setEducation("PG");
	employee2.setSalary(30000);
	
	Employee employee3 = new Employee();
	employee3.setFirstName("Martin");
	employee3.setLastName("A");
	employee3.setAge(24);
	employee3.setEducation("UG");
	employee3.setSalary(20000);
	
	Employee employee4 = new Employee();
	employee4.setFirstName("Peter");
	employee4.setLastName("M");
	employee4.setAge(25);
	employee4.setEducation("UG");
	employee4.setSalary(22000);
	
	Employee employee5 = new Employee();
	employee5.setFirstName("Roshan");
	employee5.setLastName("B");
	employee5.setAge(29);
	employee5.setEducation("PG");
	employee5.setSalary(45000);
	
	
	session.save(employee1);
	session.save(employee2);
	session.save(employee3);
	session.save(employee4);
	session.save(employee5);

	// Commit the transaction and close the session
	t.commit();
	
	session.close();
	System.out.println("successfully persisted Employee details");

   }

}


We are persisting 5 employee records to perform Criteria operations on it.

Step 7

Lets Create Main class to perform various HCQL Operations

  1. package com.kb.db;
  2.  
  3. import java.util.List;
  4.  
  5. import org.hibernate.Criteria;
  6. import org.hibernate.Session;
  7. import org.hibernate.SessionFactory;
  8. import org.hibernate.criterion.Criterion;
  9. import org.hibernate.criterion.LogicalExpression;
  10. import org.hibernate.criterion.Order;
  11. import org.hibernate.criterion.Restrictions;
  12.  
  13. import com.kb.model.Employee;
  14. import com.kb.util.HibernateUtil;
  15.  
  16. public class CriteriaExample {
  17.  
  18.     @SuppressWarnings("deprecation")
  19.     public static void main(String[] args) {
  20.         // Get session factory using Hibernate Util class
  21.         SessionFactory sf = HibernateUtil.getSessionFactory();
  22.         // Get session from Sesson factory
  23.         Session session = sf.openSession();
  24.  
  25.         Criteria criteria = session.createCriteria(Employee.class);
  26.  
  27.         // Retrieve All the Employees using Criteria
  28.         System.out.println("All the empoyees retrieved using Criteria");
  29.         displayEmployeeDetails(criteria.list());
  30.  
  31.         criteria = session.createCriteria(Employee.class);
  32.         Criterion employeeIdCriterion = Restrictions.eq("employeeId", 2);
  33.         criteria.add(employeeIdCriterion);
  34.         System.out.println("Employee record whose id is 2");
  35.         displayEmployeeDetails((Employee) criteria.uniqueResult());
  36.  
  37.         criteria = session.createCriteria(Employee.class);
  38.         Criterion greaterThanCriterion = Restrictions.gt("salary", 25000);
  39.         criteria.add(greaterThanCriterion);
  40.         System.out.println("All the empoyees whose salary is greater than 25000");
  41.         displayEmployeeDetails(criteria.list());
  42.  
  43.         criteria = session.createCriteria(Employee.class);
  44.         Criterion greaterThanOrEqualCriterion = Restrictions.ge("salary", 25000);
  45.         criteria.add(greaterThanOrEqualCriterion);
  46.         System.out.println("All the empoyees whose salary is greater than or equal to 25000");
  47.         displayEmployeeDetails(criteria.list());
  48.  
  49.         criteria = session.createCriteria(Employee.class);
  50.         Criterion lessThanCriterion = Restrictions.lt("salary", 25000);
  51.         criteria.add(lessThanCriterion);
  52.         System.out.println("All the empoyees whose salary is less than 25000");
  53.         displayEmployeeDetails(criteria.list());
  54.  
  55.         criteria = session.createCriteria(Employee.class);
  56.         Criterion lessThanOrEqualCriterion = Restrictions.le("salary", 25000);
  57.         criteria.add(lessThanOrEqualCriterion);
  58.         System.out.println("All the empoyees whose salary is less than or equal to 25000");
  59.         displayEmployeeDetails(criteria.list());
  60.  
  61.         // "Like" example
  62.         List<Employee> empList = session.createCriteria(Employee.class).add(Restrictions.like("firstName",
  63.                                                                                                   "%o%")).list();
  64.         displayEmployeeDetails(empList);
  65.  
  66.         // Pagination list example
  67.         empList = session.createCriteria(Employee.class).addOrder(Order.desc("salary")).setFirstResult(0)
  68.                 .setMaxResults(2).list();
  69.         displayEmployeeDetails(empList);
  70.  
  71.         // Combining multiple restrictions
  72.         criteria = session.createCriteria(Employee.class);
  73.         Criterion salaryGreaterThan = Restrictions.gt("salary", 25000);
  74.         Criterion ageGreaterThanOrEqual = Restrictions.ge("age", 28);
  75.         Criterion education = Restrictions.in("education", "PG", "Phd");
  76.         LogicalExpression orExp = Restrictions.or(salaryGreaterThan, ageGreaterThanOrEqual);
  77.         criteria.add(orExp);
  78.         criteria.add(education);
  79.         System.out.println(
  80.                 "All the empoyees whose salary is greater than 25000 or whose age is greater than
  81.                                  28 and educaton is either PG or Phd");
  82.         displayEmployeeDetails(criteria.list());
  83.         session.close();
  84.     }
  85.  
  86.     private static void displayEmployeeDetails(List<Employee> employeeList) {
  87.         for (Employee employee : employeeList) {
  88.             displayEmployeeDetails(employee);
  89.         }
  90.     }
  91.  
  92.     private static void displayEmployeeDetails(Employee employee) {
  93.         System.out.println(
  94.                 "ID: " + employee.getEmployeeId() + " Age: " + employee.getAge() + " Salary: " + employee.getSalary());
  95.     }
  96.  
  97. }
package com.kb.db;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.LogicalExpression;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.kb.model.Employee;
import com.kb.util.HibernateUtil;

public class CriteriaExample {

	@SuppressWarnings("deprecation")
	public static void main(String[] args) {
		// Get session factory using Hibernate Util class
		SessionFactory sf = HibernateUtil.getSessionFactory();
		// Get session from Sesson factory
		Session session = sf.openSession();

		Criteria criteria = session.createCriteria(Employee.class);

		// Retrieve All the Employees using Criteria
		System.out.println("All the empoyees retrieved using Criteria");
		displayEmployeeDetails(criteria.list());

		criteria = session.createCriteria(Employee.class);
		Criterion employeeIdCriterion = Restrictions.eq("employeeId", 2);
		criteria.add(employeeIdCriterion);
		System.out.println("Employee record whose id is 2");
		displayEmployeeDetails((Employee) criteria.uniqueResult());

		criteria = session.createCriteria(Employee.class);
		Criterion greaterThanCriterion = Restrictions.gt("salary", 25000);
		criteria.add(greaterThanCriterion);
		System.out.println("All the empoyees whose salary is greater than 25000");
		displayEmployeeDetails(criteria.list());

		criteria = session.createCriteria(Employee.class);
		Criterion greaterThanOrEqualCriterion = Restrictions.ge("salary", 25000);
		criteria.add(greaterThanOrEqualCriterion);
		System.out.println("All the empoyees whose salary is greater than or equal to 25000");
		displayEmployeeDetails(criteria.list());

		criteria = session.createCriteria(Employee.class);
		Criterion lessThanCriterion = Restrictions.lt("salary", 25000);
		criteria.add(lessThanCriterion);
		System.out.println("All the empoyees whose salary is less than 25000");
		displayEmployeeDetails(criteria.list());

		criteria = session.createCriteria(Employee.class);
		Criterion lessThanOrEqualCriterion = Restrictions.le("salary", 25000);
		criteria.add(lessThanOrEqualCriterion);
		System.out.println("All the empoyees whose salary is less than or equal to 25000");
		displayEmployeeDetails(criteria.list());

		// "Like" example
		List<Employee> empList = session.createCriteria(Employee.class).add(Restrictions.like("firstName", 
                                                                                                  "%o%")).list();
		displayEmployeeDetails(empList);

		// Pagination list example
		empList = session.createCriteria(Employee.class).addOrder(Order.desc("salary")).setFirstResult(0)
				.setMaxResults(2).list();
		displayEmployeeDetails(empList);

		// Combining multiple restrictions
		criteria = session.createCriteria(Employee.class);
		Criterion salaryGreaterThan = Restrictions.gt("salary", 25000);
		Criterion ageGreaterThanOrEqual = Restrictions.ge("age", 28);
		Criterion education = Restrictions.in("education", "PG", "Phd");
		LogicalExpression orExp = Restrictions.or(salaryGreaterThan, ageGreaterThanOrEqual);
		criteria.add(orExp);
		criteria.add(education);
		System.out.println(
				"All the empoyees whose salary is greater than 25000 or whose age is greater than 
                                  28 and educaton is either PG or Phd");
		displayEmployeeDetails(criteria.list());
		session.close();
	}

	private static void displayEmployeeDetails(List<Employee> employeeList) {
		for (Employee employee : employeeList) {
			displayEmployeeDetails(employee);
		}
	}

	private static void displayEmployeeDetails(Employee employee) {
		System.out.println(
				"ID: " + employee.getEmployeeId() + " Age: " + employee.getAge() + " Salary: " + employee.getSalary());
	}

}

We have written many criteria on the Employee entity in the above class.

Criteria criteria = session.createCriteria(Employee.class);

This line creates the criteria object on Employee entity.

criteria.list()

This line retrieves the result from DB based on all the specified criteria.

Criterion employeeIdCriterion = Restrictions.eq("employeeId", 2);

This line creates a criterion by applying a restriction on employeeId property to fetch only the record whose employeeId is 2.

Criterion greaterThanCriterion = Restrictions.gt("salary", 25000);

This line creates a criterion by applying a restriction on salary property to fetch only those records whose salary is greater than 25000.

Criterion greaterThanOrEqualCriterion = Restrictions.ge("salary", 25000);

This line creates a criterion by applying a restriction on salary property to fetch only those records whose salary is greater than or equal to 25000.

Criterion lessThanCriterion = Restrictions.lt("salary", 25000);

This line creates a criterion by applying a restriction on salary property to fetch only those records whose salary is less than 25000.

Criterion lessThanOrEqualCriterion = Restrictions.le("salary", 25000);

This line creates a criterion by applying a restriction on salary property to fetch only those records whose salary is less than or equal to 25000.

List empList = session.createCriteria(Employee.class).add(Restrictions.like("firstName", "%o%")).list();

This single line is performing multiple things,creating criteria and adding restriction to that whose firstName has a letter ‘o’ in it.

empList = session.createCriteria(Employee.class).addOrder(Order.desc("salary")).setFirstResult(0)

.setMaxResults(2).list();

This single line is performing multiple things,creating criteria and setting starting and maximum records to achieve pagination and it is also setting the order of records to be sorted in descending order on Salary property.

  1. criteria = session.createCriteria(Employee.class);
  2.         Criterion salaryGreaterThan = Restrictions.gt("salary", 25000);
  3.         Criterion ageGreaterThanOrEqual = Restrictions.ge("age", 28);
  4.         Criterion education = Restrictions.in("education", "PG", "Phd");
  5.         LogicalExpression orExp = Restrictions.or(salaryGreaterThan, ageGreaterThanOrEqual);
  6.         criteria.add(orExp);
  7.         criteria.add(education);
criteria = session.createCriteria(Employee.class);
		Criterion salaryGreaterThan = Restrictions.gt("salary", 25000);
		Criterion ageGreaterThanOrEqual = Restrictions.ge("age", 28);
		Criterion education = Restrictions.in("education", "PG", "Phd");
		LogicalExpression orExp = Restrictions.or(salaryGreaterThan, ageGreaterThanOrEqual);
		criteria.add(orExp);
		criteria.add(education);

In the above piece of code , we are creating multiple restrictions on different properties and then combining these restrictions in criteria to fetch the result accordingly.

First restriction is salary greater than 25000
Second restriction is age greater than 28
Third restriction is education which should be either PG or Phd.
But we have added first 2 restrictions using or Condition , so matching anyone in those 2 is also fine

Step 8

Run PopulateData.java class to create the initial data

Check the output in MYSQL DB

E:\MySql_Install\bin
Mysql –u root –p
Enter password

Use javainsimpleway;

Select * from Employee;

populateAggregateDataOutput

We can see that Emploeyee table has 5 records.

Step 9

Run the main class CriteriaExample to check the output of HCQL operations

Output

Download this project HibernateCriteria.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on