Hibernate Named Native SQL in XML Returning Scalar

In this section, you will learn to execute Hibernate named native SQL query written in XML mapping file which return scalar values(raw values).

Hibernate Named Native SQL in XML Returning Scalar

Hibernate Named Native SQL in XML Returning Scalar

In this section, you will learn to execute Hibernate named native SQL query written in XML mapping file which return scalar values(raw values).

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 this example, we will write Named Native SQL in XML mapping file( hibernate.cfg.xml ) inside <sql-query> tag. For returning scalar or raw values we will use <return-scalar> tag. You can see all this configuration in hibernate.cfg.xml.

We execute the query by passing the conditional where clause value using getNamedQuery() and  setString() method. Below, you can check this in the HibernateNamedNativeSQLXMLReturnScalar.java file. Since query returning scalar or raw values, we need to use setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP) which converts converts each row of result into a Map.

The project hierarchy and the jar files used is given below :


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

<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://</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> 


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;


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

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

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

<sql-query name="findViaWorkerId">
<return-scalar column="worker_id" type="long" />
<return-scalar column="firstname" type="string" />
<return-scalar column="cell_phone" type="string" />
select worker_id,firstname,cell_phone from worker w where w.worker_id= :workerId


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 HibernateNamedNativeSQLXMLReturnScalar {
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");
serviceRegistry = new ServiceRegistryBuilder().applySettings(
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 in XML Mapping Returning Scalar Value***");
Session session = sf.openSession();
try {
Query query = session.getNamedQuery("findViaWorkerId").setString("workerId", "13");
List workers = query.list();

for (Object object : workers) {
Map row = (Map) object;
System.out.println("Worker ID: " + row.get("worker_id"));
System.out.println("First Name: " + row.get("firstname"));
System.out.println("Cell Phone: " + row.get("cell_phone"));
} catch (HibernateException e) {
if (session.getTransaction() != null)
} finally {


*** Hibernate Named Native SQL Query in XML Mapping Returning Scalar Value***
Hibernate: select worker_id,firstname,cell_phone from worker w where w.worker_id= ?
Worker ID: 13
First Name: Somesh
Cell Phone: 919595959090

Download Source Code