Hibernate Native SQL Example

This Hibernate Example shows you how to use Native Query in your hibernate application.

Ads

Tutorials   
Doctype Hibernate-configuration 5 Hibernate 5 Dialect Hibernate 5 configuration dtd Hibernate 5 Hello World Getting started with Hibernate 5 Hibernate 5.2.10 jar Download Hibernate 5.2.10 Maven Dependency Hibernate 5 Maven Dependency Hibernate 5 native query example Hibernate 5 query deprecated When should you use Hibernate? What's new in Hibernate 5? How much time it takes to learn Hibernate? Hibernate envers custom revinfo table Hibernate 5 Envers Hibernate Envers get all revisions Hibernate Examples Hibernate 5 build SessionFactory Example Hibernate 5 SessionFactory Example Hibernate 5 Annotation Example How to download Hibernate 5.x? Hibernate 5 Features Hibernate 5 Tutorials Learning Hibernate ORM - Free Training/Tutorial videos of Hibernate ORM with Java How to write hello world example program in Hibernate? How to create one to one relationship in Hibernate 4 with Annotation? How to calculate minimum in Hibernate using the min() Function Hibernate ORM 4.2.21.Final Released - Create CURD application in latest Hibernate Hibernate ORM 4.2.21 Tutorial - Learn Hibernate ORM Framework Hibernate Error: Failed to create sessionFactory object.java.lang.NoClassDefFoundError How to create Hibernate Project in Eclipse? Examples of Hibernate Criteria Query Hibernate ORM 4.3.6.Final released Hibernate ORM 4.2.14.Final released Hibernate 4.3.4 Released: Hibernate 4.3.4.Final Maven dependency Hibernate association and join example Learn Hibernate programming with Examples Introduction to Hibernate Framework Hibernate Tutorial: Learn Hibernate with examples Hibernate 4.3 Hello World: Example

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.

Advertisements

 

We have 1000s of tutorials on our website. Search Tutorials tutorials on our website.

Share on Google+Share on Google+

Hibernate Native SQL Example

Posted on: August 6, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

Ads
 

Discuss: Hibernate Native SQL Example   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:3
ramu
October 14, 2011
explanation

explanation is also required for the examples
Vishwajit
January 13, 2012
How to execute following SQL query in hibernate

Suppose, We have a table emp(empid, empname, mgrid). I want to display result like empid, empname, mgrname. This is a sql query to generate this result :- select e.empid, e.empname, (select m.empname from emp m where m.empid=e.mgrid) as mgrname from emp e; Please, tell how to execute this query though createQuesry()/createSQLQuesry().
John
May 29, 2012
Excelent example!

Thanks for this example!

Ads

 

Ads