Hibernate Named Queries Example

Hibernate provides @NamedQueries template using which you can associate unique query name to query.
Since Named Queries are global access , their name should be unique. You can use Named Queries in XML Mappings or using Annotation.

If You are using XML instead of annotation then you can add Named Queries as below in Hibernate hbm.xml file. It should be after Class tags.

       <![CDATA[from Customer cust where cust.customerType = :customerType]]>

Hibernate Names Queries Tutorial using Annotation:

package com.anuj.core.entities;

import java.io.Serializable;

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

   query="from Customer cust where cust.customerType = :customerType"

@Table(name = "customer")
public class Customer implements Serializable{

 private String customerId;
 private String customerName;
 private String customerType;

 public Customer(){
 public Customer(String customerName,String customerType){
  this.customerName = customerName;
  this.customerType = customerType;
 public String getCustomerId() {
  return customerId;

 public void setCustomerId(String customerId) {
  this.customerId = customerId;

 public String getCustomerName() {
  return customerName;

 public void setCustomerName(String customerName) {
  this.customerName = customerName;

 public String getCustomerType() {
  return customerType;

 public void setCustomerType(String customerType) {
  this.customerType = customerType;


HibernateUtils :
package com.anuj.hibernate.utils;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtils {

 private static SessionFactory sessionFactory = buildSessionFactory();
 private static SessionFactory buildSessionFactory(){
  try {
   return new AnnotationConfiguration().configure().buildSessionFactory();
  } catch (Throwable ex) {
   // TODO: handle exception
   System.err.println("Initialization of Session Factory Failed");
   throw new ExceptionInInitializerError(ex);
 public static SessionFactory getSessionFactory(){
  return sessionFactory;

Hibername Configuration Xml :


Note that Transaction commit and rollback mentioned below will be useful when query will be insert/update/delete.

CustomerApp :
package com.anuj.main;

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.anuj.core.entities.Customer;
import com.anuj.hibernate.utils.HibernateUtils;

public class CustomerApp {

 private static Session session = null;
 public static void main(String[] args) {
  CustomerApp customerApp = new CustomerApp();
  * Retrieve Existing Customer
  * @param customerType
 public void retrieveCustomer(String customerType){
  Transaction transaction = null;
  try {
   session = HibernateUtils.getSessionFactory().openSession();
   transaction = session.beginTransaction();
   Query query = session.getNamedQuery("retrieveCustomerByType");
   List customer = query.list();
   Iterator itr = customer.iterator();
    Customer cust = (Customer)itr.next();
    System.out.println("CustomerId : "+cust.getCustomerId());
    System.out.println("Customer Name : "+cust.getCustomerName());
    System.out.println("Customer Type : "+cust.getCustomerType());        
  } catch (HibernateException e) {
   if(session != null){

Output :
CustomerId : 1
Customer Name : Anuj
Customer Type : Business
CustomerId : 10
Customer Name : Zvika
Customer Type : Business
CustomerId : 11
Customer Name : David
Customer Type : Business
CustomerId : 6
Customer Name : Prithvi
Customer Type : Business

No comments:

Post a Comment