Home Hibernate Hibernate4 Hibernate Criteria Restrictions
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Hibernate Criteria Restrictions

Advertisement
In this tutorial you will learn about to add the Restrictions in Criteria query.

Hibernate Criteria Restrictions

In this tutorial you will learn about to add the Restrictions in Criteria query.

In Hibernate there is an elegant way to execute the dynamically written query for this Hibernate provides Criteria API. To write a Criteria query programmatically a createCriteria() method of Session interface is used. A Criteria object created by the createCriteria() method returns the instances of the persistent object's class at the time of criteria query executed. Along with the Criteria objects Restrictions can also be added using the add() method. In Hibernate criteria queries can be restricted, to restrict the criteria queries in Hibernate an interface Criterion is used this interface is responsible for representing a query criterion as an object oriented this query might be used in a Criteria query to make it restricted. org.hibernate.criterion.Restrictions class is a factory class that provides the built-in criterion, using these built-in criterion restrictions can be added to the criteria query however, Hibernate also provides the facility of custom Restrictions creation. To specify the custom restrictions an interface org.hibernate.criterion.Criterion is implemented.

This class provides the static methods some of them are as follows :

Method Description
allEq() Used to apply an "equals" constraint to each property in the key set of a Map
and() Gives the conjunction of two expressions
or() Gives the disjunction of two expressions
not() Gives the negation of an expression
in() Used to apply an "in" constraint to the specified property
ge() Used to apply a "greater than or equal" constraint to the specified property
le() Used to apply a "less than or equal" constraint to the specified property
lt() Used to apply a "less than " constraint to the specified property

Example :

An example is being given below will demonstrate you to how can a criteria query result can be restricted. This is a very simple example where I will use the built-in criterion to restrict the criteria query results. In this example I have use the lt("propertyName", value) built-in criterion to restrict the query result, this method will return those properties values from the table of which specified propertyName value is less than the specified value as parameter of this method.

Table goodsdealer1

CREATE TABLE `goodsdealer1` ( 
`goodsDealerId` int(15) NOT NULL, 
`orderedGoodsName` varchar(15) default NULL, 
`numOfGoodsOrder` int(20) default NULL, 
`priceOfGoods` int(10) default NULL 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 

GoodsDealer1.java

package roseindia;

public class GoodsDealer1 {
private int goodsDealerId;
private int numOfGoodsOrder;
private int priceOfGoods;
private String orderedGoodsName;


public GoodsDealer1()
{
super();
}
public GoodsDealer1(int priceOfGoods, int goodsDealerId, int numOfGoodsOrder, String orderedGoodsName)
{
this.priceOfGoods = priceOfGoods;
this.goodsDealerId = goodsDealerId;
this.numOfGoodsOrder = numOfGoodsOrder;
this.orderedGoodsName = orderedGoodsName;
}
public int getPriceOfGoods() {
return priceOfGoods;
}
public void setPriceOfGoods(int priceOfGoods) {
this.priceOfGoods = priceOfGoods;
}
public int getGoodsDealerId() {
return goodsDealerId;
}
public void setGoodsDealerId(int goodsDealerId) {
this.goodsDealerId = goodsDealerId;
}
public int getNumOfGoodsOrder() {
return numOfGoodsOrder;
}
public void setNumOfGoodsOrder(int numOfGoodsOrder) {
this.numOfGoodsOrder = numOfGoodsOrder;
}
public String getOrderedGoodsName() {
return orderedGoodsName;
}
public void setOrderedGoodsName(String orderedGoodsName) {
this.orderedGoodsName = orderedGoodsName;
}
}

GoodsDealer1.hbm.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="roseindia">
<class name= "GoodsDealer1" table="goodsdealer1">
<id name= "goodsDealerId" type="int" column="goodsDealerId">
</id>
<property name="numOfGoodsOrder">
<column name="numOfGoodsOrder"/>
</property>
<property name="orderedGoodsName">
<column name="orderedGoodsName"/>
</property>
<property name="priceOfGoods">
<column name="priceOfGoods"/>
</property>
</class>

</hibernate-mapping>

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.10.13:3306/data
</property>
<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>
</session-factory>

</hibernate-configuration>

HibernateCriteriaRestrictionsExample.java

package roseindia;

import java.util.List;

import java.util.Iterator;

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 HibernateCriteriaRestrictionsExample {

static private SessionFactory sessionFactory=null;
static private ServiceRegistry serviceRegistry=null;

public static void main(String args[])
{
Session session= null;
try
{
Configuration cfg = new Configuration().addResource("roseindia/GoodsDealer1.hbm.xml");
cfg.configure();
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);
}
try
{
session = sessionFactory.openSession();
Criteria criteria = session.createCriteria(GoodsDealer1.class);
List ls = criteria.add(Restrictions.lt("numOfGoodsOrder", 125)).list();
Iterator it = ls.iterator();
while(it.hasNext())
{
GoodsDealer1 gd = (GoodsDealer1)it.next();
System.out.println(gd.getGoodsDealerId()+"\t"+gd.getOrderedGoodsName()+"\t"+gd.getNumOfGoodsOrder()+"\t"+gd.getPriceOfGoods());
}

}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}

Output :

table goodsdealer1

When you will execute the java file HibernateCriteriaRestrictionsExample.java (RightClick -> Run As -> Java Application) a query and the output will be displayed on your console :

Query will be as follows :

INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Mar 26, 2012 1:30:43 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select this_.goodsDealerId as goodsDea1_0_0_, this_.numOfGoodsOrder as numOfGoo2_0_0_, this_.orderedGoodsName as orderedG3_0_0_, this_.priceOfGoods as priceOfG4_0_0_ from goodsdealer1 this_ where this_.numOfGoodsOrder<?

And the output will be as follows :

Download Source Code

Advertisements

Liked it!  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.

Posted on: March 26, 2012

Ask Questions?    Discuss: Hibernate Criteria Restrictions  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com