Share on Google+Share on Google+

Hibernate Narrowing Criteria Result Set

In this tutorial you will learn how to narrow the Criteria result set.

Hibernate Narrowing Criteria Result Set

In this tutorial you will learn how to narrow the Criteria result set.

In Hibernate result set can be narrowed by using the restriction criteria. A custom restriction criteria is specified by implementing the org.hibernate.criterion.Criterion interface. To obtain the certain built-in Criterion types a class org.hibernate.criterion.Restrictions provides the factory method.

Example :

An example given below will demonstrates how can you narrow the result set. For creating this example at first I have created a table named worker in MySQL then created a POJO/Persistent class of which object is used to be persisted. Then created a mapping file to map the class property with the table, and a configuration file using which Hibernate creates a connection pool and required environment set up. Next created a main class where obtained a SessionFactory using ServiceRegistry then created a Session using SessionFactory. Next I have created an instance of Criteria and uses the Restrictions class for Narrowing the result set. Here I have used the static method like() of Restrictions class to retrieve the result by matching the firstname property of class.

Table worker

CREATE TABLE `worker` ( 
`workerId` int(10) NOT NULL auto_increment, 
`firstname` varchar(15) default NULL, 
`lastname` varchar(15) default NULL, 
`cellphone` varchar(11) default NULL, 
PRIMARY KEY (`workerId`) 

package roseindia;

public class Worker {
int workerId;
String firstname;
String lastname;
String cellphone;

public Worker() {


public Worker(String firstname, String lastname, String phone) {
this.firstname = firstname;
this.lastname = lastname;
this.cellphone = phone;


public int getWorkerId() {
return workerId;

public void setWorkerId(int workerId) {
this.workerId = workerId;

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 String getCellphone() {
return cellphone;

public void setCellphone(String cellphone) {
this.cellphone = cellphone;



<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate mapping DTD//EN"

<hibernate-mapping package="roseindia">
<class name= "Worker" table="worker">
<id name= "workerId" type="int" column="workerId">
<generator class="native"/>
<property name="firstname">
<column name="firstname"/>
<property name="lastname">
<column name="lastname"/>
<property name="cellphone">
<column name="cellphone"/>



<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"

<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>


package roseindia;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateNarrowingCriteriaResultSet 
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;

public static void main(String args[])
Session session = null;
Configuration cfg= new Configuration().addResource("roseindia/Worker.hbm.xml");
serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
catch(Throwable th)
System.err.println("Failed to create sessionFactory object."
+ th);
throw new ExceptionInInitializerError(th);
session = sessionFactory.openSession();
Criteria criteria = session.createCriteria(Worker.class);
criteria.add("firstname", "Ankit"));
List<Worker> ls = criteria.list();
Iterator<Worker> it = ls.iterator();
System.out.println("WorkerId \t FirstName \t LastName \t CellPhone");
Worker worker =;
System.out.println(worker.getWorkerId()+"\t\t "+worker.getFirstname()+" \t "+worker.getLastname()+" \t "+worker.getCellphone());
catch(Exception e)

Output :

Table worker

When you will execute the java file (RightClick -> RunAs -> JavaApplication) the following Query will be generated by the Hibernate :

INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Mar 16, 2012 3:25:41 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select this_.workerId as workerId0_0_, this_.firstname as firstname0_0_, this_.lastname as lastname0_0_, this_.cellphone as cellphone0_0_ from worker this_ where this_.firstname like ?

And the narrowed result set will be displayed to you as :

Download Source Code


Posted on: March 20, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Hibernate Narrowing Criteria Result Set  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image