Magazine
 
Hibernate Query Language

and query by example (QBE).
Lets take an example of query by criteria
(QBC) using Expressions. This example is
taking the same table Insurance as we have
used in our previous issue.

Consider the following table Insurance having
such records:

ID insurance_name invested_amount investement_date
2 Life Insurance 250000000-00-00 00:00:00
1 Jivan Dhara 200002007-07-30 17:29:05
3 Life Insurance 500 2005-10-15 00:00:00
4 Car Insurance 2500 2005-01-01 00:00:00
5 Dental Insurance 500 2004-01-01 00:00:00
6 Life Insurance 900 2003-01-01 00:00:00
7 Travel Insurance 2000 2005-02-02 00:00:00

Here is the code of the class using “eq” Expression:

package javajzzup.hibernate;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
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.Expression;
public class
HibernateCriteriaQueryExpressionEq {

 

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Session sess = null;
try{
SessionFactory fact = new
Configuration().configure().buildSessionFactory();
sess = fact.openSession();
Criteria crit =
sess.createCriteria(Insurance.class);
DateFormat format = new
SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);
Date date = (Date)format.parse(“2005-
01-01 00:00:00”);
crit.add(Expression.eq(“investementDate”,date));
List list = crit.list();
for(Iterator it =
list.iterator();it.hasNext();){
Insurance ins = (Insurance)it.next();
System.out.println(“Id: “ +
ins.getLngInsuranceId());
System.out.println(“Insurance Name: “
+ ins.getInsuranceName());
System.out.println(“Insurance Amount:
“ + ins.getInvestementAmount());
System.out.println(“Investement Date: “ +
ins.getInvestementDate());
}
sess.clear();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}

In the above code the crit.add(Expression.eq (“investementDate”,date)); uses two parameter e.g. eq(“property_name”,Object val). It fetches those records from the table that meets the specified date.

The output of this program will be shown as:

Mar 2008 | Java Jazz Up | 48
 
previous
index
next
 
View All Topics
All Pages of this Issue
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

30
, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 , 54, 55, 56, 57,

58
, 59,

Download PDF