Criteria Queries Implementation – Hibernate
Hibernate provides org.hibernate.criteria interface to create Criteria Queries.

Consider an example, We have an entity class named “Employee”  then our criteria query will look like,

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

Adding Restrictions:
To use condition-based criteria queries in hibernate application we need to add restrictions to the query. Here let us see some examples of adding restrictions to Hibernate Queries.

Before proceeding to example, let us see some of the standard Restrictions.

.add(Restrictions.eq(Propertyname, object value) – This will compare the property name equals to the object value

.add(Restrictions.gt(Propertyname, object value) – This will return the results when the value of that property is greater than the specified value

.add(Restrictions.lt(Propertyname, object value) – This will return the results when the value of that property is lesser than the specified value

.add(Restrictions.ge(Propertyname, object value) – This will return the results when the value of that property is greater than or equal to the specified value

.add(Restrictions.le(Propertyname, object value) – This will return the results when the value of that property is lesser than or equal to the specified value

.add(Restrictions.like(Propertyname, object value) – This will compare the propertywith specified pattern

.add(Restrictions.between(Propertyname, object low, object high) – This method compares the property within the range of low and high

Now let us see an example,

Structure
structure1

Lets create a table in Database for this example and enter some values,

table

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>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">URL</property>
    <property name="hibernate.connection.username">username</property>
    <property name="hibernate.connection.password">password</property>
    <mapping resource="com/javainfinite/pojo/CriteriaExample.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

hibernate.reveng.xml

<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
  <schema-selection match-catalog="hibernateannotation"/>
  <table-filter match-name="criteria_example"/>
</hibernate-reverse-engineering>

NewHibernateUtil.java

package com.javainfinite.pojo;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

public class NewHibernateUtil {

    private static final SessionFactory sessionFactory;
    
    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

CriteriaExample.java

package com.javainfinite.pojo;
// Generated Dec 6, 2015 7:54:21 PM by Hibernate Tools 4.3.1



/**
 * CriteriaExample generated by hbm2java
 */
public class CriteriaExample  implements java.io.Serializable {


     private int sno;
     private String uname;
     private Integer money;
     private String city;

    public CriteriaExample() {
    }

	
    public CriteriaExample(int sno) {
        this.sno = sno;
    }
    public CriteriaExample(int sno, String uname, Integer money, String city) {
       this.sno = sno;
       this.uname = uname;
       this.money = money;
       this.city = city;
    }
   
    public int getSno() {
        return this.sno;
    }
    
    public void setSno(int sno) {
        this.sno = sno;
    }
    public String getUname() {
        return this.uname;
    }
    
    public void setUname(String uname) {
        this.uname = uname;
    }
    public Integer getMoney() {
        return this.money;
    }
    
    public void setMoney(Integer money) {
        this.money = money;
    }
    public String getCity() {
        return this.city;
    }
    
    public void setCity(String city) {
        this.city = city;
    }
}

CriteriaExample.hbm.xml

<hibernate-mapping>
    <class name="com.javainfinite.pojo.CriteriaExample" table="criteria_example" catalog="hibernateannotation" optimistic-lock="version">
        <id name="sno" type="int">
            <column name="sno" />
            <generator class="assigned" />
        </id>
        <property name="uname" type="string">
            <column name="uname" length="30" />
        </property>
        <property name="money" type="java.lang.Integer">
            <column name="Money" />
        </property>
        <property name="city" type="string">
            <column name="city" length="30" />
        </property>
    </class>
</hibernate-mapping>

Controller.java

package com.javainfinite.controller;

import com.javainfinite.pojo.CriteriaExample;
import com.javainfinite.pojo.NewHibernateUtil;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

public class Controller {
    
     public static void main(String args[])
    {
        
        Session session = NewHibernateUtil.getSessionFactory().openSession();
        Transaction trans=session.beginTransaction();
        Criteria criteria = session.createCriteria(CriteriaExample.class).add(Restrictions.eq("city", "Berlin"));
        List l1= criteria.list();
        for( Iterator itr = l1.iterator(); itr.hasNext();)
        {
            CriteriaExample ce=(CriteriaExample) itr.next();
            System.out.println(ce.getUname() + " "+ ce.getMoney()+ " " + ce.getCity());
        } 
       trans.commit();
    }   
}


Output:

Criteria criteria = session.createCriteria(CriteriaExample.class).add(Restrictions.eq("city", "Berlin"));

This is print the records that matches the city name Berlin

eq

Output 2:

Criteria criteria = session.createCriteria(CriteriaExample.class).add(Restrictions.gt("money", 15000));

Prints records which has money property value more than 15000

gt

Output 3:

Criteria criteria = session.createCriteria(CriteriaExample.class).add(Restrictions.le("money", 15000));

Prints records which has money property value less than or equal to 15000

le

Output 4:

Criteria criteria = session.createCriteria(CriteriaExample.class).add(Restrictions.like("city", "%A%"));

Prints records whose city name property contains “A”

like

 Output 5:

Criteria criteria = session.createCriteria(CriteriaExample.class).add(Restrictions.between("money", 15000, 22000));

Prints records whose money property value is between 15000 and 22000

between

 

 

By Sri

One thought on “Criteria Queries Implementation – Hibernate”

Leave a Reply

Your email address will not be published. Required fields are marked *