JavaBeat
calling cards | international calling cards | phone card
Search JavaBeat

JAVABEAT
home
articles
tips
QnA
Books
forums
ARTICLE TOPICS
All Articles
Java 5.0
Java 6.0
EJB 3.0
JCA
Struts
JSF
Spring
Groovy
JBoss Seam
Hibernate
Eclipse
JavaFx
Google Guice
J2ME
GWT
WebServices
AJAX
ARCHIVE
2007 | 12 11 10 09 08 07 06 05 04 03
2008 | 07 06 05 04 03 02 01
CERTIFICATION KITS
350 SCJP 1.5 Mock Exams
400 SCJP 1.6 Mock Exams
300 SCWCD 5.0 Mock Exams
300 SCBCD 5.0 Mock Exams
Enter email address:

Latest JavaBeat Articles Delivered by FeedBurner
OUR NETWORK
javabeat
planetoss

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:


import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.criterion.*;
import org.hibernate.cfg.*;
import java.util.*;
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 = (Insuranceit.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.




Favorites
Buy movies
Access Control
Busby seo challenge contest
Sohbet
Chat
Webmaster Hosting Forum
Java Jobs
MyVideoLib
India News
Internet Advances
Sohbet
chat
Latest QnA
SCJD Tips
When we start a thread by applying start() method on it ,how does it knows that to execute run()method?
About Wrapper class in Java
How to configure weblogic 7.0 in MyEclipse?
Static Block and Static Initializer in Java

JavaBeat Website (2004-2008), India
javabeat | about us | planetoss
Copyright (2004 - 2008), JavaBeat