Hibernate Named Query (XML Mapping)

We don’t like to see HQL string literals scattered all over the Java code unless they’re necessary. Hibernate lets you externalize query strings to the mapping metadata, a technique that is called named queries. This allows you to store all queries related to a particular persistent class (or a set of classes) encapsulated with the other metadata of that class in an XML mapping file. The name of the query is used to call it from the application.

The getNamedQuery() method obtains a Query instance for a named query:

session.getNamedQuery("findEmployeeByName").setString("name", "Puneet");

In this example, we execute the named query findEmployeeByName after binding a string argument to a named parameter. The named query is defined in mapping metadata, e.g. in Employee.hbm.xml, using the <query> element:

<query name="findEmployeeByName">
    <from Employee emp where emp.name = :name]]>

Named queries don’t have to be HQL strings; they might even be native SQL queries – and your Java code doesn’t need to know the difference:

<sql-query name="findItemsByDescription">
<![CDATA[select {emp.*} from Employee {emp} where NAME like :name
<return alias="emp" class="Employee"/>

First create a new Java Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml


1. Sql Script

Use the following Sql Script for creating table.

create table Employee(
    EMPLOYEE_ID int(10) primary key NOT NULL AUTO_INCREMENT,
    Name varchar(50));

2. Pojo

Now Create Employee Class as following.

package com.kruders.model.bean;

public class Employee {
    private int employeeId;
    private String name;
    public Employee() {
    public Employee(String name) {
        this.name = name;
    public int getEmployeeId() {
        return employeeId;
    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    public String getName() {
        return name;
    public void setName(String name) {
        this.name = name;

3. Hibernate Mapping File

Now create HBM file Employee.hbm.xml that maps classes to database tables.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<class name="com.kruders.model.bean.Employee" table="EMPLOYEE">
    <meta attribute="class-description">This class contains employee details.</meta>
    <id name="employeeId" type="int" column="EMPLOYEE_ID">
        <generator class="native" />
    <property name="name" type="string" length="50" column="NAME" />
<query name="findEmployeeByName">
    	<![CDATA[from Employee emp where emp.name = :name]]>

4. Hibernate Configuration File

Now create the hibernate configuration file and add all the mapping files.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
	<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
	<property name="hibernate.connection.username">root</property>
	<property name="hibernate.connection.password"></property>
	<property name="connection.pool_size">1</property>
	<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
	<property name="show_sql">true</property>
	<mapping resource="com/kruders/model/bean/Employee.hbm.xml"/>

5. Hibernate Utility Class

Now create HibernateUtil class. The HibernateUtil class helps in creating the SessionFactory from the Hibernate configuration file. A org.hibernate.SessionFactory is used to obtain org.hibernate.Session instances. A org.hibernate.Session represents a single-threaded unit of work. The org.hibernate.SessionFactory is a thread-safe global object that is instantiated once.

package com.kruders.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();
    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
    public static SessionFactory getSessionFactory() {
        return sessionFactory;

6. Run Program

Create Main.java that calls the named query with getNamedQuery method which takes the name of the query as parameter and run it as Java Application

package com.kruders.core;

import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.kruders.model.bean.Employee;
import com.kruders.util.HibernateUtil;

public class Main {
	public static void main(String args[]) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            Query query = session.getNamedQuery("findEmployeeByName").setString("name", "Puneet");
            List employees = query.list();
            for (Iterator iterator = employees.iterator(); iterator.hasNext();) {
                Employee employee = (Employee) iterator.next();
                System.out.println("Name " + employee.getName());
        }catch (HibernateException e) {
        } finally {

The folder structure of the example is shown below in Figure 17.1

Figure 17.1 Figure 17.1

You can download the source code of this example here.

No comments yet.

Leave a Reply