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:
   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 Facing Programming Problem? Ask Questions?, Browse Latest Questions, Question-Answer Guidelines
Hibernate
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments
Hibernate Native SQL Example
This Hibernate Example shows you how to use Native Query in your hibernate application.
 
 

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
 = 
(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.

                         

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

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.

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

Current Comments

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

Hi,

It will be better if the benefits and drawbacks between each type i.e; between HQL and criteria and Native SQL with examples.

Posted by Sandeep on Tuesday, 06.3.08 @ 11:26am | #61923

hi,

this is laxman from hyd,

it is wonderful site for getting more information & examples on required specific technologies.

Posted by laxman on Tuesday, 11.13.07 @ 17:21pm | #37228

This tutorial its great job !

all examples works without problems :)
... and it's easy to use

Posted by Emiliozzz on Thursday, 07.19.07 @ 15:21pm | #21567

hi,
it is good.it helped me lot. if u provide some exxcess info like how to trnas from the data into dtos directly from querys. it will be the best.


Thanks&Regards
sunil k

Posted by sunil on Friday, 07.13.07 @ 14:40pm | #21207

This example use for java, so how I can write by c#?
Thanks!

Posted by Tam Phan on Thursday, 05.10.07 @ 12:10pm | #15555

THATS PERFECT BUT WHAT ABOUT STORED PROCEDURES?
GREETINGS

Posted by Omar on Saturday, 03.10.07 @ 05:08am | #11290


hi,
How to delete data using hibernate on webpage.


nice...

Posted by Hanumath on Friday, 02.9.07 @ 17:17pm | #6983

i heartfully thanks to RoseIndia. This article will help me more and more, to learn easily. But i got one doubt, am working with stored procedures in native sql but its not working properly please send some sample source code then i can understand easily...once again thanks to RoseIndia.

Posted by srinivas on Friday, 02.9.07 @ 13:14pm | #6943

Deepak,

Good work. I really appreciate your work. Thanks a lot!
- Arun

Posted by Arun on Tuesday, 02.6.07 @ 16:31pm | #6409

Hi sir,
This article is nice. I want to know ,how can I call the procedures from hibernate.please send any example program or other resources.

regards satya

Posted by satya on Wednesday, 01.31.07 @ 12:32pm | #4868

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

Indian Software Development Company | iPhone Development Company in India | Java Training Delhi | Java Training at Noida |

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

Copyright © 2008. All rights reserved.