Named querey is a concept which separate the query from coding section to hbm file with a specific   name. Which we can use by calling its name. It can be reusable.  can be native sql or hql.

We are taking here one simple query , fetching records whose salary<11000.

These are the steps for achieving it

  1. Create The Employee bean class
    package com.bullraider.nsq;
    import java.io.Serializable;
    import java.io.Serializable;
    public class Employee implements Serializable{
    	private long empno;
    	private String ename;
    	private int sal;
    	private String job;
    	private int deptno ;
    	Employee(){
    
    	}
    	public Employee( String ename, String job, int sal,int deptno) {
    		super();
    		this.deptno = deptno;
    		this.empno = empno;
    		this.ename = ename;
    		this.job = job;
    		this.sal = sal;
    		//this.employeeAddress=employeeAddress;
    	}
    	public long getEmpno() {
    		return empno;
    	}
    
    	public void setEmpno(long empno) {
    		this.empno = empno;
    	}
    
    	public String getEname() {
    		return ename;
    	}
    	public void setEname(String ename) {
    		this.ename = ename;
    	}
    	public int getSal() {
    		return sal;
    	}
    	public void setSal(int sal) {
    		this.sal = sal;
    	}
    	public String getJob() {
    		return job;
    	}
    	public void setJob(String job) {
    		this.job = job;
    	}
    	public int getDeptno() {
    		return deptno;
    	}
    	public void setDeptno(int deptno) {
    		this.deptno = deptno;
    	}
    
    	}
    
    
  2. Design emp.hbm.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC
    	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
    	<class name="com.bullraider.nsq.Employee" table="emp200">
    		<meta attribute="class-description"> This class contains employee details. </meta>
    		<id name="empno" type="long" column="empno">
    			<generator class="native" />
    		</id>
    		<property name="ename" type="string" column="ename" not-null="true" />
    		<property name="job" type="string" column="job" not-null="true" />
    		<property name="sal" type="integer" column="sal" not-null="true" />
    		<property name="deptno" type="integer" column="deptno"
    			not-null="true" />
    	</class>
    	<query name="selectEmp">
    <![CDATA[ from Employee  where sal<11000 ]]>
    	</query>
    </hibernate-mapping>
    
  3. HibernateUtil Class to get the SessionFactory
    package com.bullraider.nsq;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    
    public class HibernateUtil {
    	private static final SessionFactory sessionFactory;
    	static {
    		try {
    			sessionFactory = new Configuration().configure()
    					.buildSessionFactory();
    		} catch (Throwable ex) {
    			System.err.println("SessionFactory creation failed" + ex);
    			throw new ExceptionInInitializerError(ex);
    		}
    	}
    
    	public static SessionFactory getSessionFactory() {
    		return sessionFactory;
    	}
    }
    
    
  4. Create the main class
    package com.bullraider.nsq;
    
    
    import java.util.Iterator;
    import java.util.List;
    
    import org.hibernate.HibernateException;
    import org.hibernate.Query;
    import org.hibernate.Session;
    import org.hibernate.Transaction;
    public class EmployeeDao {
    
    	public static void main(String[] args) {
    		EmployeeDao dao=new EmployeeDao();
    		dao.saveEmployee();
    		dao.retriveEmployee();
    
    	}
    	public void saveEmployee()
    
    	{
    
    		Session session = HibernateUtil.getSessionFactory().openSession();
    		Transaction transaction = null;
    		Long empId = null;
    		try {
    			transaction = session.beginTransaction();
    			Employee emp1=new Employee("Alok","SALESMAN",2000,10);
    			Employee emp2=new Employee("Bhibhu","MGR",2000,20);
    			Employee emp3=new Employee("Ameet","SALESMAN",18000,10);
    			Employee emp4=new Employee("Prasdeep","CLERK",10000,10);
    			session.save(emp1);
    			session.save(emp2);
    			session.save(emp3);
    			session.save(emp4);
    			EmployeeDao dao=new EmployeeDao();
    			dao.retriveEmployee();
    			transaction.commit();
    			System.out.println("Records inserted sucessessfully");
    		} catch (HibernateException e) {
    			transaction.rollback();
    			e.printStackTrace();
    		} finally {
    			session.close();
    		}
    
    
    	}
    	public void retriveEmployee() 
    
    	{ 
    
    		Session session = HibernateUtil.getSessionFactory().openSession(); 
    		Transaction transaction = null; 
    		try { 
    			transaction = session.beginTransaction(); 
    			System.out.println("HI");
    			List emp= session.getNamedQuery("selectEmp").list(); 
    			System.out.println("Size is"+" "+emp.size());
    			System.out.println("HI");
    			for (Iterator iterator = emp.iterator(); iterator.hasNext();) 
    			{ 
    				Employee employee1 = (Employee) iterator.next(); 
    				System.out.println(employee1.getEname()+"  "+
    						employee1.getSal()); 
    			}           
    			transaction.commit(); 
    
    		} catch (HibernateException e) { 
    
    			transaction.rollback(); 
    
    			e.printStackTrace(); 
    
    		} finally { 
    
    			session.close(); 
    		} 
    	}
    
    
    }
    
    
    
    
  5. This is the hibernate.cfg.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-configuration PUBLIC
    		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
        <session-factory>
            <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
            <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:ORCL</property>
            <property name="hibernate.connection.username">scott</property>
            <property name="connection.password">cat</property>
            <property name="connection.pool_size">1</property>
            <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
            <property name="show_sql">true</property>
           <property name="hbm2ddl.auto">create-drop</property>
            <mapping resource="com/bullraider/nsq/Employee.hbm.xml"/>
        </session-factory>
    </hibernate-configuration>
    
    

Download Named-sql-query.zip