Named Query using annotation

  • Facebook
  • Google
  • LinkedIn
  • Twitter

We have seen named query example using hibernate mapping in the previous example now we learn named query using annotations. So @NamedQueries and @NamedQuery are annotations can be defined at the class level.

@NameQueries: this annotation is used to define the multiple named queries.

@NameQuery: this annotation is used to define the single named query.

@NamedNativeQueries: this annotation is used to define the multiple native sql named queries.

@NamedNativeQuery: this annotation is used to define the single native sql named query.

Named Query example using annotation

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>

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="com.javatutsworld.hibernate.pojo.Employee"/>
	</session-factory>
</hibernate-configuration>

Employee.java

package com.javatutsworld.hibernate.pojo;

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

//Native sql named queries
@NamedNativeQueries({
		@NamedNativeQuery(name = "@sql_select", query = "select * from employee"),
		@NamedNativeQuery(name = "@sql_select_with_param", query = "select * from employee where empid=?") })

// Hql named queries
@NamedQueries({
		@NamedQuery(name = "hql_select", query = "from Employee e"),
		@NamedQuery(name = "hql_select_with_param", query = "from Employee e where e.empId=?"),
		@NamedQuery(name = "hql_select_with_named_param", query = "from Employee e where e.empId=:empId") })

@Entity
@Table(name = "employee")
public class Employee {
	@Id
	@GeneratedValue
	@Column(name = "EMPID")
	private int empId;
	@Column(name = "EMPNAME")
	private String empName;
	@Column(name = "EMPAGE")
	private int empAge;
	@Column(name = "EMPSALARY")
	private long empSalary;
	@Column(name = "EMPADDRESS")
	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;
	}

}

It is a persistent class that uses annotations to define hql named queries and Native sql named queries and marks this class as entity.

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