Named Query Using Mapping File

  • Facebook
  • Google
  • LinkedIn
  • Twitter

Named Query is a way to use queries by giving a name and will be defined at one place so that it can be used same query multiple times anywhere in the project.

Advantages Disadvantages
  • Named Queries are compiled and validated when the SessionFactory is instantiated at application start-up time.
  • Named Queries are accessed globally, once defined it can be used anywhere in the application.
  • Named Queries provide significant performance benefit because each named queries are compiled at startup which means repeatable executions uses the same compiled queries.
Named Queries are static so we would not be able to change these queries within a running application server without reloading the SessionFactory.

Named query is supported in both HQL and native SQL. Here are two ways to define the named query in hibernate.

  • Using mapping file.
  • Using annotation.

Named Query using mapping file

Table:  employee

Columns: 
EMPID 		int(11) AI PK 
EMPNAME 	varchar(20) 
EMPAGE 		int(11) 
EMPSALARY 	bigint(20) 
EMPADDRESS 	varchar(20) 

Pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Named-Query-Example</groupId>
	<artifactId>Named-Query-Example</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.3.0.Final</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.34</version>
		</dependency>
	</dependencies>
</project>

Mapping file employee.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.javatutsworld.hibernate.pojo.Employee" table="employee">
		<id name="empId" column="EMPID" />
		<property name="empName" column="EMPNAME" />
		<property name="empAge" column="EMPAGE" />
		<property name="empSalary" column="EMPSALARY" />
		<property name="empAddress" column="EMPADDRESS" />
	</class>
	<!-- Native sql named queries -->
	<sql-query name="sql_select">select * from employee</sql-query>
	<sql-query name="sql_select_with_param">select * from employee where empid=?</sql-query>
	
	<!-- Hql named queries -->
	<query name="hql_select">from Employee e</query>
	<query name="hql_select_with_param">from Employee e where e.empId=?</query>
	<query name="hql_select_with_named_param">from Employee e where e.empId=:empId</query>
</hibernate-mapping>

Place the native sql named query and hql named query inside hibernate-mapping element after the class element but if we put before the class element then Hibernate will prompt invalid mapping file.

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="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/sys</property>
		<property name="connection.username">root</property>
		<property name="connection.password">admin123</property>
		<property name="show_sql">true</property>
		<mapping resource="employee.hbm.xml" />
	</session-factory>
</hibernate-configuration>

Employee.java

package com.javatutsworld.hibernate.pojo;

public class Employee {
	private int empId;
	private String empName;
	private int empAge;
	private long empSalary;
	private String empAddress;

	public int getEmpId() {
		return empId;
	}

	public void setEmpId(int empId) {
		this.empId = empId;
	}

	public String getEmpName() {
		return empName;
	}

	public void setEmpName(String empName) {
		this.empName = empName;
	}

	public int getEmpAge() {
		return empAge;
	}

	public void setEmpAge(int empAge) {
		this.empAge = empAge;
	}

	public long getEmpSalary() {
		return empSalary;
	}

	public void setEmpSalary(long empSalary) {
		this.empSalary = empSalary;
	}

	public String getEmpAddress() {
		return empAddress;
	}

	public void setEmpAddress(String empAddress) {
		this.empAddress = empAddress;
	}

}

HibUtility.java

package com.javatutsworld.hibernate.pojo;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibUtility{
	private static SessionFactory factory;

	private HibUtility() {
	}

	public synchronized static SessionFactory getSessionFactory() {
		if (factory == null) {
			factory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
		}
		return factory;
	}

	@Override
	protected Object clone() throws CloneNotSupportedException {
		// TODO Auto-generated method stub
		return new RuntimeException("Clone not Supported **********  !");
	}

}

MainApp.java

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.javatutsworld.hibernate.pojo.Employee;
import com.javatutsworld.hibernate.pojo.HibUtility;

public class MainApp {

	public static void main(String[] args) {
		SessionFactory factory = HibUtility.getSessionFactory();
		Session openSession = factory.openSession();
		System.out.println("*********SQL SELECT***********");
		Query query = openSession.getNamedQuery("sql_select");
		List list = query.list();
		Iterator iterator = list.iterator();
		while (iterator.hasNext()) {
			Object[] object = (Object[]) iterator.next();
			System.out.println("empId : " + object[0] + " empName : " + object[1]+ " empAge : " + object[2]+ " empSalary : " +object[3]+ " empAddress : " +object[4]);
		}

		System.out.println("*********sql_select_with_param***********");
		Query query5 = openSession.getNamedQuery("sql_select_with_param").setString(0, "1");
		List list5 = query5.list();
		Iterator iterator5 = list5.iterator();
		while (iterator5.hasNext()) {
			Object[] object = (Object[]) iterator5.next();
			System.out.println("empId : " + object[0] + " empName : " + object[1]+ " empAge : " + object[2]+ " empSalary : " +object[3]+ " empAddress : " +object[4]);
		}

		System.out.println("*********HQL SELECT***********");
		Query query2 = openSession.getNamedQuery("hql_select");
		List list2 = query2.list();
		Iterator iterator2 = list2.iterator();
		while (iterator2.hasNext()) {
			Employee emp = (Employee) iterator2.next();
			System.out.println("empId : " + emp.getEmpId()+ " empName : " + emp.getEmpName() + " empAge : "+ emp.getEmpAge() + " empSalary : " +emp.getEmpSalary() + " empAddress : " +emp.getEmpAddress());
		}

		System.out.println("*********hql_select_with_param***********");
		Query query3 = openSession.getNamedQuery("hql_select_with_param").setString(0, "1");
		List list3 = query3.list();
		Iterator iterator3 = list3.iterator();
		while (iterator3.hasNext()) {
			Employee emp = (Employee) iterator3.next();
			System.out.println("empId : " + emp.getEmpId()+ " empName : " + emp.getEmpName() + " empAge : "+ emp.getEmpAge() + " empSalary : " +emp.getEmpSalary() + " empAddress : " +emp.getEmpAddress());
		}

		System.out.println("*********hql_select_with_named_param***********");
		Query query4 = openSession.getNamedQuery("hql_select_with_named_param").setString("empId", "1");
		List list4 = query4.list();
		Iterator iterator4 = list4.iterator();
		while (iterator4.hasNext()) {
			Employee emp = (Employee) iterator4.next();
			System.out.println("empId : " + emp.getEmpId()+ " empName : " + emp.getEmpName() + " empAge : "+ emp.getEmpAge() + " empSalary : " +emp.getEmpSalary() + " empAddress : " +emp.getEmpAddress());
		}
	}

}

Output

*********SQL SELECT***********
Hibernate: select * from employee
empId : 1 empName : Gaurav Pantola empAge : 32 empSalary : 4500 empAddress : Noida Ext
*********sql_select_with_param***********
Hibernate: select * from employee where empid=?
empId : 1 empName : Gaurav Pantola empAge : 32 empSalary : 4500 empAddress : Noida Ext
*********HQL SELECT***********
Hibernate: select employee0_.EMPID as EMPID1_0_, employee0_.EMPNAME as EMPNAME2_0_, employee0_.EMPAGE as EMPAGE3_0_, employee0_.EMPSALARY as EMPSALAR4_0_, employee0_.EMPADDRESS as EMPADDRE5_0_ from employee employee0_
empId : 1 empName : Gaurav Pantola empAge : 32 empSalary : 4500 empAddress : Noida Ext
*********hql_select_with_param***********
Hibernate: select employee0_.EMPID as EMPID1_0_, employee0_.EMPNAME as EMPNAME2_0_, employee0_.EMPAGE as EMPAGE3_0_, employee0_.EMPSALARY as EMPSALAR4_0_, employee0_.EMPADDRESS as EMPADDRE5_0_ from employee employee0_ where employee0_.EMPID=?
empId : 1 empName : Gaurav Pantola empAge : 32 empSalary : 4500 empAddress : Noida Ext
*********hql_select_with_named_param***********
Hibernate: select employee0_.EMPID as EMPID1_0_, employee0_.EMPNAME as EMPNAME2_0_, employee0_.EMPAGE as EMPAGE3_0_, employee0_.EMPSALARY as EMPSALAR4_0_, employee0_.EMPADDRESS as EMPADDRE5_0_ from employee employee0_ where employee0_.EMPID=?
empId : 1 empName : Gaurav Pantola empAge : 32 empSalary : 4500 empAddress : Noida Ext
      Advertisements