Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML
 
 
Search All Tutorials
  

 
Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML
 
Hibernate
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

Hibernate Select Clause

                         

In this lesson we will write example code to select the data from Insurance table using Hibernate Select Clause. The select clause picks up objects and properties to return in the query result set. Here is the query:

Select insurance.lngInsuranceId, insurance.insuranceName, insurance.investementAmount, insurance.investementDate from Insurance insurance

which selects all the rows (insurance.lngInsuranceId, insurance.insuranceName, insurance.investementAmount, insurance.investementDate) from Insurance table.

Hibernate generates the necessary sql query and selects all the records from Insurance table. Here is the code of our java file which shows how select HQL can be used:


package roseindia.tutorial.hibernate;

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

import java.util.*;

/**
 @author Deepak Kumar
 *
 * http://www.roseindia.net
 * HQL Select Clause Example
 */
public class SelectClauseExample {
  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();
     
    //Create Select Clause HQL
     String SQL_QUERY ="Select insurance.

lngInsuranceId,insurance.insuranceName," 
     "insurance.investementAmount,insurance.

investementDate from Insurance insurance";
 Query query = session.createQuery(SQL_QUERY);
 for(Iterator it=query.iterate();it.hasNext();){
       Object[] row = (Object[]) it.next();
       System.out.println("ID: " + row[0]);
       System.out.println("Name: " + row[1]);
       System.out.println("Amount: " + row[2]);
     }
     
        session.close();
  }catch(Exception e){
    System.out.println(e.getMessage());
  }finally{
    }
  }
}

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

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_

ID: 1

Name: Car Insurance

Amount: 1000

ID: 2

Name: Life Insurance

Amount: 100

ID: 3

Name: Life Insurance

Amount: 500

ID: 4

Name: Car Insurance

Amount: 2500

ID: 5

Name: Dental Insurance

Amount: 500

ID: 6

Name: Life Insurance

Amount: 900

ID: 7

Name: Travel Insurance

Amount: 2000

ID: 8

Name: Travel Insurance

Amount: 600

ID: 9

Name: Medical Insurance

Amount: 700

ID: 10

Name: Medical Insurance

Amount: 900

ID: 11

Name: Home Insurance

Amount: 800

ID: 12

Name: Home Insurance

Amount: 750

ID: 13

Name: Motorcycle Insurance

Amount: 900

ID: 14

Name: Motorcycle Insurance

Amount: 780

                         

Facing Programming Problem?
Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

16 comments so far (post your own) View All Comments Latest 10 Comments:

Because this site is used by both begniner and expert in Java, The code should close the connection in the finally block as it make the code more company standard and it will be easy for fresher to under how a code should be written.

Posted by Rakesh Sharma on Tuesday, 08.26.08 @ 10:59am | #75199

I'm asking for help when i run the example ie give me this Exception:
Exception in thread "main" java.lang.NoClassDefFoundError: org/dom4j/DocumentException
at example.Test.main(Test.java:24)
Caused by: java.lang.ClassNotFoundException: org.dom4j.DocumentException
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
... 1 more

there is my source java:
package example;

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

public class Test {
public static void main(String[] args) {
Session session = null;

try{
// This step will read hibernate.cfg.xml
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
model.xxxUtilisateur qu= new xxxUtilisateur();
qu.setLogin("admin");
System.out.println("L'utlisateur"+qu.getLogin()+"est crée");
session.save(qu);
System.out.println("L'utlisateur"+qu.getLogin()+"est ajouté a la base de donnée");
session.close();

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

Posted by hi on Wednesday, 03.19.08 @ 14:54pm | #53306

xception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:110)
at tutorial.hibernate.SelectClauseExample.main(SelectClauseExample.java:15)

Posted by Shaheer on Tuesday, 03.11.08 @ 11:31am | #52259

where can i findout the answers

Posted by tej on Thursday, 12.6.07 @ 21:45pm | #41470

very nice

Posted by tej on Thursday, 12.6.07 @ 21:43pm | #41469

I tried to run above program but I didn't any result here is the outcome. Please let me know what needs to be done.

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
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_
could not execute query using iterate

Posted by Syed on Thursday, 11.29.07 @ 20:58pm | #40909

Simple and easy to learn for new people. Its really the place for quick learners.

Posted by Raghava on Saturday, 10.20.07 @ 17:06pm | #34453

The select clause picks up objects and properties to return in the query result set. But i want to return the collection bean objects from select clause. how? is there any other way to get that ?
Please help me ?

Posted by P.M.Rushi on Thursday, 02.8.07 @ 13:43pm | #6773

Is there any link from where i can find all the clause of hql with example.

Posted by RIK on Monday, 02.5.07 @ 12:56pm | #6137

I'm getting mad!
even if i read almost all tutorials in the net, I still can't translate the following query from sql to hql!
can anyone help me?
the query is:

SELECT AVG(Expr) AS Result
FROM (
SELECT COUNT(*) + 1 AS Expr
FROM dbo.DISPONIBILITA)

Posted by Sasa on Thursday, 01.18.07 @ 15:29pm | #3761

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Hot Web Programming Job

Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2007. All rights reserved.