Sunday, March 30, 2014

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:

Customer.java
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;

@NamedQueries({
 @NamedQuery(
   name="retrieveCustomerByType",
   query="from Customer cust where cust.customerType = :customerType"
 )
})

/**
 * 
 * @author Anuj
 * @source goldenpackagebyanuj.blogspot.com
 */
@Entity
@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;
 }
 
 @Id
 @GeneratedValue
 @Column(name="CustomerId",nullable=false,unique=true)
 public String getCustomerId() {
  return customerId;
 }

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

 @Column(name="CustomerName",nullable=false)
 public String getCustomerName() {
  return customerName;
 }

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

 @Column(name="CustomerType",nullable=false)
 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;

/**
 * 
 * @author Anuj
 * @source goldenpackagebyanuj.blogspot.com
 */
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 :

 
  com.mysql.jdbc.Driver
  PASSWORD
  jdbc:mysql://localhost/DBNAME
  USERNAME
  org.hibernate.dialect.MySQLDialect
  false
  
 


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;

/**
 * 
 * @author Anuj
 * @source goldenpackagebyanuj.blogspot.com
 */
public class CustomerApp {

 private static Session session = null;
 
 public static void main(String[] args) {
  
  CustomerApp customerApp = new CustomerApp();
  customerApp.retrieveCustomer("Business");
 }
 
 /**
  * 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");
   query.setParameter("customerType",customerType);
   
   List customer = query.list();
   Iterator itr = customer.iterator();
   
   while(itr.hasNext()){
    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());        
   }
   
   transaction.commit();
   
  } catch (HibernateException e) {
   transaction.rollback();
   e.printStackTrace();   
  }
  finally{
   if(session != null){
    session.close();
   }
  }
 } 
}


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

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/