Hibernate Named Native SQL Query using XML Mapping

In this section, you will learn Named Native SQL Query using XML Mapping in Hibernate with an example.

Ads

Tutorials   
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 4.3.4 Released: Hibernate 4.3.4.Final Maven dependency Hibernate 4.3 Hello World: Example How to create SessionFactory in Hibernate 4.3.1? Hibernate 4 Hello World: Example of Hello World program Hibernate 4 create Session Factory: Example of creating Session Factory in Hibernate 4 Hibernate 4.3 and JPA 2.1 Example What is Hibernate in Java? Hibernate Overview and Architecture What is JPA 2.1? Hibernate 4.3.0.Final Maven dependency Hibernate 4.3 ORM Features Hibernate 4.3 Tutorial Hibernate Criteria average example Hibernate Criteria load all objects from table Hibernate Criteria Hibernate beginner tutorial Hibernate Session.delete() Example Hibernate save or update method example Hibernate Load Example Hibernate save Example - Rose India Hibernate 4 tutorials Hibernate Example Step by Step in Eclipse Hibernate Configuration files Setup Hibernate Environment Hibernate Architecture Hibernate Overview Hibernate 4.2 Tutorial Hibernate 4 Annotations Tutorial Hibernate 4 AnnotationSessionFactoryBean hibernate versions hibernate jndi hibernate tomcat hibernate metamodel generator hibernate entity Seam Hibernate C3P0 Hibernate hibernate shard hibernate means temporal hibernate jsf hibernate spring j2ee hibernate spring hibernate encrypted password alias_to_entity_map hibernate temporal jsf spring hibernate hibernate by example hibernate repository hibernate sample code
Ads

Hibernate Named Native SQL Query using XML Mapping

In this section, you will learn Named Native SQL Query using XML Mapping in Hibernate with an example.

Using HQL or criteria query in Hibernate, you can execute nearly any type of SQL query. Even so some developer complaint about slowness of statement generated by Hibernate and they opt to generate their own SQL statement. This explicitly generated query is known as Hibernate Native SQL Query.

In Named SQL Query using XML Mapping, we will write Named Native SQL query inside <sql-query> tag in XML mapping file. You can check this in the below example in Worker.hbm.xml file.

We execute the query by passing the conditional where clause value using getNamedQuery() and  setString() method. Below, you can check this in the HibernateNamedNativeSQLXML.java file.

EXAMPLE

The project hierarchy is given below :

The Worker.hbm.xml is given below :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="net.roseindia">

<class name="Worker" table="worker">
<id name="workerId" column="worker_id">
<generator class="native" />
</id>
<property name="firstname" column="firstname" />
<property name="lastname" column="lastname" />
<property name="birthDate" type="date" column="birth_date" />
<property name="cellphone" column="cell_phone" />

</class>
<sql-query name="findViaWorkerId">
<return alias="worker" class="net.roseindia.Worker"/>
<![CDATA[select * from worker w where w.worker_id = :workerId]]>
</sql-query>
</hibernate-mapping>

The code for Worker. java is given below :

package net.roseindia;

import java.util.Date;

public class Worker {

private Long workerId;

private String firstname;

private String lastname;

private Date birthDate;

private String cellphone;

public Worker() {

}

public Worker(String firstname, String lastname, Date birthdate,
String phone) {
this.firstname = firstname;
this.lastname = lastname;
this.birthDate = birthdate;
this.cellphone = phone;

}

public Long getWorkerId() {
return workerId;
}

public void setWorkerId(Long workerId) {
this.workerId = workerId;
}

public String getFirstname() {
return firstname;
}

public void setFirstname(String firstname) {
this.firstname = firstname;
}

public String getLastname() {
return lastname;
}

public void setLastname(String lastname) {
this.lastname = lastname;
}

public Date getBirthDate() {
return birthDate;
}

public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}

public String getCellphone() {
return cellphone;
}

public void setCellphone(String cellphone) {
this.cellphone = cellphone;
}
}

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://192.168.10.13:3306/anky</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>

<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">validate</property> 
</session-factory>
</hibernate-configuration>

HibernateNamedNativeSQLXML.java

package net.roseindia;

import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateNamedNativeSQLXML {
private static SessionFactory sf;
private static ServiceRegistry serviceRegistry;

public static void main(String[] args) {
try {
Configuration configuration = new Configuration().addResource("net/roseindia/Worker.hbm.xml");
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
sf = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
System.out.println("*** Hibernate Named Native SQL Query with XML Mapping ***");
System.out.println("----------------------------------------------------------");
Session session = sf.openSession();
try {
session.beginTransaction();
Query query = session.getNamedQuery("findViaWorkerId").setString("workerId", "13");
List workers = query.list();

for (Iterator iterator = workers.iterator(); iterator.hasNext();) {
Worker worker = (Worker) iterator.next();
System.out.println("Worker Id:" + worker.getWorkerId());
System.out.println("Worker Name:" + worker.getFirstname());
System.out.println("Worker Birth Date:" + worker.getBirthDate());
System.out.println("Worker CellPhone No."+ worker.getCellphone());
System.out.println("-----------------------------------------------------------");
}
session.getTransaction().commit();
} catch (HibernateException e) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}

OUTPUT

After execution, you will get the following result on console :

*** Hibernate Named Native SQL Query with XML Mapping ***
----------------------------------------------------------
Hibernate: select * from worker w where w.worker_id = ?
Worker Id:13
Worker Name:Somesh
Worker Birth Date:1987-07-21
Worker CellPhone No.919595959090
-----------------------------------------------------------

Download Source Code

Advertisements

Ads
Share on Google+Share on Google+

Hibernate Named Native SQL Query using XML Mapping

Posted on: March 23, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

Ads
 

Discuss: Hibernate Named Native SQL Query using XML Mapping  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:1
swan
July 12, 2013
Why use CDATA for SQL-Query in mapping file?

Hi, I've noticed in your example that the SQL query within the sql-query XML element is itself, wrapped in CDATA. Why was that done? I ask because the hibernate 3.0 DTD specifies the contents of the sql-query XML element to be PCDATA. Was this found to be the 'secret' to getting it to work? swan

Ads

 

Ads