Share on Google+Share on Google+

HQL Where Clause Example

Where Clause is used to limit the results returned from database.

HQL Where Clause Example


Where Clause is used to limit the results returned from database. It can be used with aliases and if the aliases are not present in the Query, the properties can be referred by name. For example:

from Insurance where lngInsuranceId='1'

Where Clause can be used with or without Select Clause. Here the example code:

package roseindia.tutorial.hibernate;

import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.cfg.*;

import java.util.*;

 @author Deepak Kumar
 * HQL Where Clause Example
 * Where Clause With Select Clause Example
public class WhereClauseExample {
  public static void main(String[] args) {
  Session session = null;

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

  SessionFactory sessionFactory = new 
  session =sessionFactory.openSession();
  System.out.println("Query using 
Hibernate Query Language"
  //Query using Hibernate Query Language
 String SQL_QUERY =" from Insurance
 as insurance where insurance.
 Query query = session.createQuery
 for(Iterator it=query.iterate()
 Insurance insurance=(Insurance)it
 System.out.println("ID: " + insurance.
 System.out.println("Name: " 
+ insurance. getInsuranceName());
 System.out.println("Where Clause With
 Select Clause"
  //Where Clause With Select Clause
 SQL_QUERY ="Select insurance.
insurance.investementDate from Insurance
 insurance "
" where insurance.
 query = session.createQuery(SQL_QUERY);
 for(Iterator it=query.iterate();it.
 Object[] row = (Object[]);
 System.out.println("ID: " + row[0]);
 System.out.println("Name: " + row[1]);

  }catch(Exception e){

To run the example select Run-> Run As -> Java Application from the menu bar. Following out is displayed in the Eclipse console:


Query using Hibernate Query Language

Hibernate: select insurance0_.ID as col_0_0_ from insurance insurance0_ where (insurance0_.ID='1')

ID: 1

Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?

Name: Car Insurance


Where Clause With Select Clause

Hibernate: select insurance0_.ID as col_0_0_, insurance0_.insurance_name as col_1_0_, insurance0_.invested_amount as col_2_0_, insurance0_.investement_date as col_3_0_ from insurance insurance0_ where (insurance0_.ID='1')

ID: 1

Name: Car Insurance



Posted on: January 19, 2008 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: HQL Where Clause Example   View All Comments

Post your Comment

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