Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Hibernate Hibernate4 Hibernate Native Scalar Query

Related Tutorials


 
 

Share on Google+Share on Google+

Hibernate Native Scalar Query

Advertisement
In this section, you will learn Hibernate Native Scalar Query .

Hibernate Native Scalar Query

In this section, you will learn Hibernate Native Scalar Query .

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. These developer generated query is known as Hibernate Native SQL Query.

Hibernate Native Scalar Query is the most basic SQL query. In this query, we fetch list of scalars or values from one or more database tables.

EXAMPLE

In the below example, we are fetching three scalars (values) from worker table which are firstname, birth_date, cell_phone. For handling query results, we are using  setResultTransformer( Criteria.ALIAS_TO_ENTITY_MAP )  method which converts each row of result into a Map.

The project hierarchy is given below :

The query for creating table worker is given below :

CREATE TABLE `worker` ( 
`worker_id` bigint(10) NOT NULL auto_increment, 
`firstname` varchar(50) default NULL, 
`lastname` varchar(50) default NULL, 
`birth_date` date NOT NULL, 
`cell_phone` varchar(15) NOT NULL, 
PRIMARY KEY (`worker_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1

CODE

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>

<mapping class="net.roseindia.Worker"/>

</session-factory>
</hibernate-configuration>

Worker.java

package net.roseindia;

import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "worker")
public class Worker {

@Id
@GeneratedValue
@Column(name = "worker_id")
private Long workerId;



@Column(name = "firstname")
private String firstname;

@Column(name = "lastname")
private String lastname;

@Column(name = "birth_date")
private Date birthDate;

@Column(name = "cell_phone")
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;
}
}

HibernateNativeScalarQuery.java

package net.roseindia;

import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
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 HibernateNativeScalarQuery {
private static SessionFactory sf;
private static ServiceRegistry serviceRegistry;

public static void main(String[] args) {
try {
Configuration configuration = new Configuration();
configuration.configure()
.setProperty("hibernate.show_sql", "false");
;
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 Native Scalar Query Example***");
System.out.println("-------------------------------------------");
Session session = sf.openSession();
try {
session.beginTransaction();
String sql = "SELECT firstname, birth_date,cell_phone FROM worker";
Query query = session.createSQLQuery(sql);
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List data = query.list();

for (Object object : data) {
Map row = (Map) object;
System.out.println("First Name: " + row.get("firstname"));
System.out.println("Birth Date: " + row.get("birth_date"));
System.out.println("Cell Phone: " + row.get("cell_phone"));
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 results on console:

***Hibernate Native Scalar Query Example***
-------------------------------------------
First Name: Sushmita
Birth Date: 1987-05-21
Cell Phone: 919595959595
-------------------------------------------
First Name: Nayana
Birth Date: 1987-06-30
Cell Phone: 919191919191
-------------------------------------------
First Name: Sameer
Birth Date: 1981-09-30
Cell Phone: 919191929292
-------------------------------------------

Download Source Code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: March 17, 2012

Related Tutorials

Discuss: Hibernate Native Scalar Query  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:1
droope
August 10, 2012
Brilliant!

Brilliant! thanks
DMCA.com