Hibernate Named Query using Annotation

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 the same file using Annotations. 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 class using Annotation:

    name = "findEmployeeByName",
    query = "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:

    name = "findEmployeeByName",
    query = "select * from Employee emp where emp.name = :name",
    resultClass = Stock.class

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 PURCHASE_ORDERS (
    street varchar(255) not null,
    city varchar(255) not null,
    itemName varchar(255),
    primary key (street, city)

2. Pojo

Now create Employee class.

package com.kruders.model.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

	name = "findEmployeeByName",
	query = "from Employee emp where emp.name = :name"

@Table(name = "EMPLOYEE")
public class Employee {
    @GeneratedValue(strategy= GenerationType.AUTO)
    @Column(name = "EMPLOYEE_ID")
	private int employeeId;
	@Column(name = "Name")
    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 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 class="com.kruders.model.bean.Employee" />

4. 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;

5. Run Program

Create Main.java class 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 18.1

Figure 18.1 Figure 18.1

You can download the source code of this example here.

No comments yet.

Leave a Reply