Showing posts with label Hibernate Query Language. Show all posts
Showing posts with label Hibernate Query Language. Show all posts

Hibernate Subqueries

In this section, you will learn about the subqueries with an appropriate example.

Subqueries in hibernate can be referred as the queries that are surrounded by parentheses (). Subqueries solves the purpose of grouping, ordering , narrowing and aggregating the resultant of the query by using the where clause. Notice that the subqueries get executed prior to the main query. The HQL queries may contain the subqueries only in case of if the subqueries are supported by the underline database.

A unidirectional one-to-many association on a foreign key is rarely required.

"1.0" encoding="UTF-8"?>


PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">


<class name="net.roseindia.Dealer">
"id" type="int">
class="increment"/>


"name" type="string"/>
"product" inverse="true" cascade="all,delete-orphan">
"did"/>
class="net.roseindia.Product"/>


class>

A unidirectional one-to-many association on a foreign key is rarely required.

'1.0' encoding='utf-8'?>

PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">


<class name="net.roseindia.Product">
"id" type="int">
class="increment"/>


"name" type="string"/>
"did" type="int"/>
"price" type="double"/>
"dealer" class="net.roseindia.Dealer" column="did"
insert=
"false" update="false"/>

class>

Here is the hibernate code:

In this example first we create the session object with the help of the SessionFactory interface. Then we use the createQuery() method of the Session object which returns a Query object. Now we use the openSession() method of the SessionFactory interface simply to instantiate the Session object. And the we retrieve the data from the database store it in that Query object and iterate this object with the help of Iterator and finally displays the requested data on the console.

package net.roseindia;

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

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

public class Subqueries {

/**
* @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();
String sql_query = "select d.name,p.name,p.price from Product p join p.dealer
d where p.price in(select p.price from p where p.price > 1500)"
;
Query query = sess.createQuery(sql_query);
System.out.println("Dealer Name\t"+"Product Name\t"+"Price");
for(Iterator it=query.iterate();it.hasNext();){
Object[] row = (Object[]) it.next();
System.out.print(row[0]);
System.out.print("\t\t"+row[1]);
System.out.print("\t"+row[2]);
System.out.println();
}
sess.close();
}
catch(Exception e ){
System.out.println(e.getMessage());
}
}

}

Output:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

log4j:WARN Please initialize the log4j system properly.

Hibernate: select dealer1_.name as col_0_0_, product0_.name as col_1_0_, product0_.price as col_2_0_ from Product product0_ inner join Dealer dealer1_ on product0_.did=dealer1_.id where product0_.price in (select product0_.price from Product product0_ where product0_.price>1500)

Dealer Name Product Name Price

Agrawal Computer 23000.0

Mohan Mobile 15000.0

Ritu HardDisk 2500.0

read more “Hibernate Subqueries”

Hibernate Aggregate Functions(Associations and Joins)

This example tries to make understand about the aggregate function of Hibernate with the help of example.

In Hibernate HQL queries are capable of returning the results of the aggregate functions on properties. Collections can also be used with the aggregate functions with the select clause. Aggregate functions supports the following functions:

  • min(...), max(...), sum(...), avg(...).
  • count(*)
  • count(distinct...), count(all..), count(...)

The distinct and all keywords used above are identical as in SQL.

A unidirectional one-to-many association on a foreign key is rarely required.

"1.0" encoding="UTF-8"?>


PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net
/hibernate-mapping-3.0.dtd"
>


<class name="net.roseindia.Dealer">
"id" type="int">
class="increment"/>


"name" type="string"/>
"product" inverse="true"
cascade="all,delete-orphan">
"did"/>
class="net.roseindia.Product"/>


class>

A unidirectional one-to-many association on a foreign key is rarely required.

'1.0' encoding='utf-8'?>

PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/
hibernate-mapping-3.0.dtd"
>


<class name="net.roseindia.Product">
"id" type="int">
class="increment"/>


"name" type="string"/>
"did" type="int"/>
"price" type="double"/>
"dealer" class="
net.roseindia.Dealer"
column="did"
insert=
"false" update="false"/>

class>

In this example first we create the session object with the help of the SessionFactory interface. Then we use the createQuery() method of the Session object which returns a Query object. Now we use the openSession() method of the SessionFactory interface simply to instantiate the Session object. And the we retrieve the data from the database store it in that Query object and iterate this object with the help of Iterator and finally displays the requested data on the console.

Here is the hibernate code:

package net.roseindia;

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

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

public class AggregateFunctionExample {

/**
* @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();
String sql_query = "select
d.name,p.name,sum(p.price) as
totalprice from Product
p join p.dealer d group by p.name"
;
Query query = sess.createQuery(sql_query);
System.out.println("Dealer
Name\t"
+"Product Name\t"+"Price");
for(Iterator it=
query.iterate
();it.hasNext();){
Object[] row = (Object[]) it.next();
System.out.print(row[0]);
System.out.print("\t\t"+row[1]);
System.out.print("\t"+row[2]);
System.out.println();
}
sess.close();
}
catch(Exception e ){
System.out.println(e.getMessage());
}
}

}

Output:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

log4j:WARN Please initialize the log4j system properly.

Hibernate: select dealer1_.name as col_0_0_, product0_.name as col_1_0_, sum(product0_.price) as col_2_0_ from Product product0_ inner join Dealer dealer1_ on product0_.did=dealer1_.id group by product0_.name

Dealer Name Product Name Price

Agrawal Computer 23100.0

Ritu HardDisk 2500.0

Agrawal Keyboard 1500.0

Ritu Laptop 200.0

Mohan Mobile 15000.0

Mohan PenDrive 200.0

read more “Hibernate Aggregate Functions(Associations and Joins)”

Associations and Joins

This section includes a brief introduction about Associations and Joins along with examples.

Association mappings: Association mappings comes in the list of the most difficult thing to get right. This section includes the canonical cases one by one. Here we starts the section from unidirectional mappings and comes to the bi-directional cases.

We'll include the classification of associations that whether they map or not to an intervening join table and by multiplicity.

Here we are not using the Nullable foreign keys since these keys do not require good practice in traditional data modeling. Hibernate does not require the foreign keys since mappings work even if we drop the nullability constraints.

Hibernate HQL Inner Join

Hibernate's HQL language is not capable for handling the "inner join on" clauses. If our domain entity model includes relationships defined between the related objects then the query like this

Query query = session.createQuery("from Car car inner join Owner owner where owner.Name ='Vinod'");

will work. HQL keeps the information of joining the Car and Owner classes according to the association mapping contained in the hbm.xml file. Since the association information is defined in the mapping file so there is no need to stipulate the join in the query. In the above query "from Car car where car.Owner.Name='Vinod'" will work too. Initialization of the collections and many-to-one mapping requires the explicit joins just to avoid lazy load errors.

A unidirectional one-to-many association on a foreign key is rarely required.

"1.0" encoding="UTF-8"?>


PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/
hibernate-mapping-3.0.dtd"
>


<class name="net.roseindia.Dealer">
"id" type="int">
class="increment"/>


"name" type="string"/>
"product" inverse="
true"
cascade="all,delete-orphan">
"did"/>
class="
net.roseindia.Product"
/>


class>

A unidirectional one-to-many association on a foreign key is rarely required.

'1.0' encoding='utf-8'?>

PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/
hibernate-mapping-3.0.dtd"
>


<class name="net.roseindia.Product">
"id" type="int">
class="increment"/>


"name" type="string"/>
"did" type="int"/>
"price" type="double"/>
"dealer" class="
net.roseindia.Dealer"
column="did"
insert=
"false" update="false"/>

class>

Here is the hibernate code:

In this example first we create the session object with the help of the SessionFactory interface. Then we use the createQuery() method of the Session object which returns a Query object. Now we use the openSession() method of the SessionFactory interface simply to instantiate the Session object. And the we retrieve the data from the database store it in that Query object and iterate this object with the help of Iterator and finally displays the requested data on the console.

package net.roseindia;

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

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

public class Join {

/**
* @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();
String sql_query = "from
Product p inner join p.dealer as d"
;
Query query = sess.createQuery(sql_query);
Iterator ite = query.list().iterator();
System.out.println("Dealer
Name\t"
+"Product Name\t"+"Price");
while ( ite.hasNext() ) {
Object[] pair = (Object[]) ite.next();
Product pro = (Product) pair[0];
Dealer dea = (Dealer) pair[1];
System.out.print(pro.getName());
System.out.print("\t"+dea.getName());
System.out.print("\t\t"+pro.getPrice());
System.out.println();
}
sess.close();
}
catch(Exception e ){
System.out.println(e.getMessage());
}

}

}

Output:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

log4j:WARN Please initialize the log4j system properly.

Hibernate: select product0_.id as id1_0_, dealer1_.id as id0_1_, product0_.name as name1_0_, product0_.did as did1_0_, product0_.price as price1_0_, dealer1_.name as name0_1_ from Product product0_ inner join Dealer dealer1_ on product0_.did=dealer1_.id

Dealer Name Product Name Price

Computer Agrawal 23000.0

Keyboard Agrawal 1500.0

Computer Agrawal 100.0

Mobile Mohan 15000.0

PenDrive Mohan 200.0

Laptop Ritu 200.0

HardDisk Ritu 2500.0

read more “Associations and Joins”

Hibernate Native SQL Example

Native SQL is handwritten SQL for all database operations like create, update, delete and select. Hibernate Native Query also supports stored procedures. Hibernate allows you to run Native SQL Query for all the database operations, so you can use your existing handwritten sql with Hibernate, this also helps you in migrating your SQL/JDBC based application to Hibernate.

In this example we will show you how you can use Native SQL with hibernate. You will learn how to use Native to calculate average and then in another example select all the objects from table.

Here is the code of Hibernate Native SQL:

package roseindia.tutorial.hibernate;

import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.criterion.*;
import org.hibernate.cfg.*;
import java.util.*;
/**
* @author Deepak Kumar
*
* http://www.roseindia.net Hibernate Native Query Example
*
*/
public class NativeQueryExample {
public static void main(String[] args) {
Session session = null;

try{
// This step will read
hibernate.cfg.xml and prepare hibernate for use

SessionFactory sessionFactory =
new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
/* Hibernate Native Query Average Examle*/
String sql ="select
stddev(ins.invested_amount) as stdErr, "
+
" avg(ins.invested_amount) as mean "+
" from insurance ins";
Query query = session.createSQLQuery(sql)
.addScalar
("stdErr",Hibernate.DOUBLE).
addScalar("mean",Hibernate.DOUBLE);
//Double [] amount = (Double []) query.uniqueResult();
Object [] amount = (Object [])
query.uniqueResult();
System.out.println("mean
amount: "
+ amount[0]);
System.out.println("stdErr
amount: "
+ amount[1]);

/* Example to show Native
query to select all the
objects from database */

/* Selecting all
the objects from insurance table */

List insurance = session.createSQLQuery
("select {ins.*} from insurance ins")
.addEntity("ins", Insurance.class)
.list();
for (Iterator it =
insurance.iterator
(); it.hasNext();) {
Insurance insuranceObject
=
(Insurance) it.next();
System.out.println("ID: "
+ insuranceObject.getLngInsuranceId());
System.out.println("Name:
"
+ insuranceObject.getInsuranceName());
}

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

}
}

Following query is used to calculate the average of invested amount:

/*Hibernate Native Query Average Examle*/

String sql ="select stddev(ins.invested_amount) as stdErr, "+ " avg(ins.invested_amount) as mean "+ " from insurance ins";

The following code:

Query query = session.createSQLQuery(sql).addScalar("stdErr",Hibernate.DOUBLE).
addScalar("mean",Hibernate.DOUBLE);

Creates a new instance of SQLQuery for the given SQL query string and the entities returned by the query are detached.

To return all the entities from database we have used the following query:

/* Example to show Native query to select all the objects from database */
/* Selecting all the objects from insurance table */
List insurance = session.createSQLQuery("select {ins.*} from insurance ins")
.addEntity("ins", Insurance.class)
.list();
for (Iterator it = insurance.iterator(); it.hasNext();) {
Insurance insuranceObject = (Insurance) it.next();
System.out.println("ID: " + insuranceObject.getLngInsuranceId());
System.out.println("Name: " + insuranceObject.getInsuranceName());
}

When you run the program through it should display the following result:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

log4j:WARN Please initialize the log4j system properly.

Hibernate: select stddev(ins.invested_amount) as stdErr, avg(ins.invested_amount) as mean from insurance ins

mean amount: 592.1584

stdErr amount: 923.5714

Hibernate: select ins.ID as ID0_, ins.insurance_name as insurance2_2_0_, ins.invested_amount as invested3_2_0_, ins.investement_date as investem4_2_0_ from insurance ins

ID: 1

Name: Car Insurance

ID: 2

Name: Life Insurance

ID: 3

Name: Life Insurance

ID: 4

Name: Car Insurance

......

.......

In this example you learned how to use Native Query with Hibernate.

read more “Hibernate Native SQL Example”

Insert Data into Database Using Hibernate Native SQL

In this example we will show you how you can use Native SQL with hibernate. You will learn how to use Native to insert data into database. Native SQL is handwritten SQL for all database operations like insert, update, delete and select.

Hibernate provides a powerful query language Hibernate Query Language that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.


Step1: Create hibernate native sql for inserting data into database.

Hibernate Native uses only the Hibernate Core for all its functions. The code for a class that will be saved to the database is displayed below:

package hibernateexample;

import javax.transaction.*;
import org.hibernate.Transaction;
import org.hibernate.*;
import org.hibernate.criterion.*;
import org.hibernate.cfg.*;
import java.util.*;


public class HibernateNativeInsert {
public static void main(String args[]){
Session sess = null;
try{
sess = HibernateUtil.currentSession();
Transaction tx = sess.beginTransaction();
Studentdetail student = new Studentdetail();
student.setStudentName("Amardeep Patel");
student.setStudentAddress("rohini,sec-2, delhi-85");
student.setEmail("amar@rediffmail.com");
sess.save(student);
System.out.println("Successfully data insert in database");
tx.commit();
}
catch(Exception e){
System.out.println(e.getMessage());
}
finally{
sess.close();
}
}
}

Step 2: Create session factory 'HibernateUtil.java'.

Here is the code of session Factory:

package hibernateexample;

import java.sql.*;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.io.*;

public class HibernateUtil {
public static final SessionFactory sessionFact;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFact = new Configuration().configure().buildSessionFactory();
}
catch(Throwable e) {
System.out.println("SessionFactory creation failed." + e);
throw new ExceptionInInitializerError(e);
}
}
public static final ThreadLocal session = new ThreadLocal();

public static Session currentSession() throws HibernateException {
Session sess = (Session) session.get();
// Open a new Session, if this thread has none yet
if(sess == null){
sess = sessionFact.openSession();
// Store it in the ThreadLocal variable
session.set(sess);
}
return sess;
}
public static void SessionClose() throws Exception {
Session s = (Session) session.get();
if (s != null)
s.close();
session.set(null);
}
}

Step 3: Hibernate native uses the Plain Old Java Objects (POJOs) classes to map to the database table. We can configure the variables to map to the database column. Here is the code for "Studenetdetail.java":

package hibernateexample;

public class Studentdetail {
private String studentName;
private String studentAddress;
private String email;
private int id;

public String getStudentName(){
return studentName;
}

public void setStudentName(String studentName){
this.studentName = studentName;
}

public String getStudentAddress(){
return studentAddress;

}

public void setStudentAddress(String studentAddress){
this.studentAddress = studentAddress;
}

public String getEmail(){
return email;
}

public void setEmail(String email){
this.email = email;
}

public int getId(){
return id;
}

public void setId(int id){
this.id = id;
}
}

Here is the output:

Download here all application.

read more “Insert Data into Database Using Hibernate Native SQL”

Insert Data into Database Using Hibernate Native SQL

In this example we will show you how you can use Native SQL with hibernate. You will learn how to use Native to insert data into database. Native SQL is handwritten SQL for all database operations like insert, update, delete and select.

Hibernate provides a powerful query language Hibernate Query Language that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.


Step1: Create hibernate native sql for inserting data into database.

Hibernate Native uses only the Hibernate Core for all its functions. The code for a class that will be saved to the database is displayed below:

package hibernateexample;

import javax.transaction.*;
import org.hibernate.Transaction;
import org.hibernate.*;
import org.hibernate.criterion.*;
import org.hibernate.cfg.*;
import java.util.*;


public class HibernateNativeInsert {
public static void main(String args[]){
Session sess = null;
try{
sess = HibernateUtil.currentSession();
Transaction tx = sess.beginTransaction();
Studentdetail student = new Studentdetail();
student.setStudentName("Amardeep Patel");
student.setStudentAddress("rohini,sec-2, delhi-85");
student.setEmail("amar@rediffmail.com");
sess.save(student);
System.out.println("Successfully data insert in database");
tx.commit();
}
catch(Exception e){
System.out.println(e.getMessage());
}
finally{
sess.close();
}
}
}

Step 2: Create session factory 'HibernateUtil.java'.

Here is the code of session Factory:

package hibernateexample;

import java.sql.*;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.io.*;

public class HibernateUtil {
public static final SessionFactory sessionFact;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFact = new Configuration().configure().buildSessionFactory();
}
catch(Throwable e) {
System.out.println("SessionFactory creation failed." + e);
throw new ExceptionInInitializerError(e);
}
}
public static final ThreadLocal session = new ThreadLocal();

public static Session currentSession() throws HibernateException {
Session sess = (Session) session.get();
// Open a new Session, if this thread has none yet
if(sess == null){
sess = sessionFact.openSession();
// Store it in the ThreadLocal variable
session.set(sess);
}
return sess;
}
public static void SessionClose() throws Exception {
Session s = (Session) session.get();
if (s != null)
s.close();
session.set(null);
}
}

Step 3: Hibernate native uses the Plain Old Java Objects (POJOs) classes to map to the database table. We can configure the variables to map to the database column. Here is the code for "Studenetdetail.java":

package hibernateexample;

public class Studentdetail {
private String studentName;
private String studentAddress;
private String email;
private int id;

public String getStudentName(){
return studentName;
}

public void setStudentName(String studentName){
this.studentName = studentName;
}

public String getStudentAddress(){
return studentAddress;

}

public void setStudentAddress(String studentAddress){
this.studentAddress = studentAddress;
}

public String getEmail(){
return email;
}

public void setEmail(String email){
this.email = email;
}

public int getId(){
return id;
}

public void setId(int id){
this.id = id;
}
}

Here is the output:

Download here all application.

read more “Insert Data into Database Using Hibernate Native SQL”

Hibernate Criteria Expression (or)

In this section, you will learn to use the "or" method. This is one of the most important method that returns the disjunction of the two expressions. You can also build the nested expressions using 'and' and 'or'.
Expressions:
The Hibernate Criteria API supports a rich set of comparison operators. Some standard SQL operators are =, <, ?, >, ?.

Expression or(Criterion LHS, Criterion RHS): This method returns the disjuction of two expressions. Any given condition is 'true' then it executes the query. In this tutorial, "or" is used :

Expression.or(Expression.eq("lngInsuranceId", new Long(3), Expression.eq("IngInsuranceId", new Long(6))).

Table Name: insurance

ID insurance_name invested_amount investement_date
2 Life Insurance 25000 0000-00-00 00:00:00
1 Givan Dhara 20000 2007-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 "or" Expression :

package roseindia.tutorial.hibernate;

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

/**
* @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);
crit.add(Expression.or
(
Expression.eq("lngInsuranceId",new Long(3)),
Expression.eq
("lngInsuranceId",new Long(6))));
List list = crit.list();
for (Iterator it = list.iterator();it.hasNext();){
Insurance ins = (Insurance)it.next();
System.out.println("Insurance
Id: "
+ ins.getLngInsuranceId());
System.out.println("Insurance
Name: "
+ ins.getInsuranceName());
System.out.println("Invested
Amount: "
+ ins.getInvestementAmount());
System.out.println("Investement
Date:"
+ ins.getInvestementDate());
}
sess.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}

Download this Code.

Output:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

log4j:WARN Please initialize the log4j system properly.

Hibernate: select this_.ID as ID0_0_, this_.insurance_name as insurance2_0_0_, this_.invested_amount as invested3_0_0_, this_.investement_date as investem4_0_0_ from insurance this_ where (this_.ID=? or this_.ID=?)

Insurance Id: 3

Insurance Name: Life Insurance

Invested Amount: 500

Investement Date:2005-10-15 00:00:00.0

Insurance Id: 6

Insurance Name: Life Insurance

Invested Amount: 900

Investement Date:2003-01-01 00:00:00.0

read more “Hibernate Criteria Expression (or)”

Hibernate Criteria Expression (and)

In this section, you will learn to use the "and" method. This is one of the most important method that returns the conjunctions of two expressions. You can also build the nested expressions using 'and' and 'or'. Expressions: The Hibernate Criteria API supports a rich set of comparison operators. Some standard SQL operators are =, <, ?, >, ?.

Expression and(Criterion LHS, Criterion RHS): This method returns the conjunctions of two expressions. Both conditions are 'true' then it xecutes the query otherwise not. In this tutorial, "and" is used :

Expression.and(Expression.gt("lngInsuranceId", new Long(3), Expression.lt("IngInsuranceId", new Long(6))).

Table Name: insurance

ID insurance_name invested_amount investement_date
2 Life Insurance 25000 0000-00-00 00:00:00
1 Givan Dhara 20000 2007-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 "and" Expression :

package roseindia.tutorial.hibernate;

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

/**
* @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);
crit.add(Expression.and
(Expression.gt("lngInsuranceId",new Long(3)),
Expression.lt
("lngInsuranceId",new Long(6))));
List list = crit.list();
for(Iterator it =
list.iterator
();it.hasNext();){
Insurance ins =
(Insurance)it.next();
System.out.println(
"Insurance Id: " + ins.getLngInsuranceId());
System.out.println(
"Insurance Name: " + ins.getInsuranceName());
System.out.println(
"Invested Amount: " + ins.getInvestementAmount());
System.out.println(
"Investement Date: "
+ ins.getInvestementDate());
}
sess.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}

Download this Code.

Output:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

log4j:WARN Please initialize the log4j system properly.

Hibernate: select this_.ID as ID0_0_, this_.insurance_name as insurance2_0_0_, this_.invested_amount as invested3_0_0_, this_.investement_date as investem4_0_0_ from insurance this_ where (this_.ID>? and this_.ID

Insurance Id: 4

Insurance Name: Car Insurance

Invested Amount: 2500

Investement Date: 2005-01-01 00:00:00.0

Insurance Id: 5

Insurance Name: Dental Insurance

Invested Amount: 500

Investement Date: 2004-01-01 00:00:00.0

read more “Hibernate Criteria Expression (and)”