Named Queries in Hibernate

Let us understand about Named Queries in Hibernate


If we want to use same queries in multiple places of an application, then instead of writing same query in multiple places, we can define the query in one place with the name assigned to it and use that name in all the places wherever required.

The concept of defining the query with name in one place and accessing that query by using its query name wherever required is called Named Query.

Named query will be defined in the hibernate mapping file.

Named query can be used for both HQL queries and Native SQL queries.

Hibernate Named query example with HQL

< query name=”hql_select_employee“ >from Employee  e  where e.id=:empId< /query >

For HQL named query, < query > tag should be used.

we have given the name to it, so that we can access the query with that name from required class.

We can also pass the dynamic parameters as well to named query as shown above

Accessing the HQL named query in our class

Query query = session.getNamedQuery(“hql_select_employee”);

query.setParameter("empId",new Integer(1));


Hibernate Named query example with SQL

< sql-query name=”sql_select_employee“ >select * from Employee e where e.id=:empId</sql-query>

For SQL named query, < sql-query > tag should be used.

we have given the name to it, so that we can access the query with that name from required class.

We can also pass the dynamic parameters as well to named query as shown above.

Accessing the SQL named query in our class

Query query = session.getNamedQuery(“sql_select_employee”);

query.setParameter("empId",new Integer(1));


We can define Named query using either XML mapping or Annotation mapping.

Let us see the complete Project on Named Query

Step 1

Create hibernate project

Please refer Hibernate setup in eclipse article on how to do it.

Project structure


NamedQueryProjStructure

Step 2

Update pom.xml with MYSQL and Hibernate depenedencies

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
 
  <groupId>NamedQuery</groupId>
  <artifactId>NamedQuery</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
 
  <name>NamedQuery</name>
  <url>http://maven.apache.org</url>
 
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
 
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
     <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.6.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.5</version>
        </dependency>
  </dependencies>
</project>
<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>NamedQuery</groupId>
  <artifactId>NamedQuery</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>NamedQuery</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
     <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.2.6.Final</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>6.0.5</version>
		</dependency>
  </dependencies>
</project>

Step 3

Create Employee class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package com.kb.model;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedNativeQuery;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
 
@Entity
@Table(name = "Employee")
@NamedQuery(name = "hql_employee_select", query = "from Employee where age=:age")
@NamedNativeQuery(name = "sql_employee_select", query = "select * from Employee")
public class Employee {
 
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "Employee_Id")
    private int employeeId;
 
    @Column(name = "FirstName")
    private String firstName;
 
    @Column(name = "LastName")
    private String lastName;
 
    @Column(name = "Age")
    private int age;
 
    @Column(name = "Education")
    private String education;
 
    @Column(name = "Salary")
    private int salary;
 
    public int getEmployeeId() {
        return employeeId;
    }
 
    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }
 
    public String getFirstName() {
        return firstName;
    }
 
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
 
    public String getLastName() {
        return lastName;
    }
 
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public String getEducation() {
        return education;
    }
 
    public void setEducation(String education) {
        this.education = education;
    }
 
    public int getSalary() {
        return salary;
    }
 
    public void setSalary(int salary) {
        this.salary = salary;
    }
 
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Id:").append(employeeId).append(" FirstName:").append(firstName).append(" 
                                                                       Age:").append(age);
        return sb.toString();
    }
}
package com.kb.model;

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

@Entity
@Table(name = "Employee")
@NamedQuery(name = "hql_employee_select", query = "from Employee where age=:age")
@NamedNativeQuery(name = "sql_employee_select", query = "select * from Employee")
public class Employee {

	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE)
	@Column(name = "Employee_Id")
	private int employeeId;

	@Column(name = "FirstName")
	private String firstName;

	@Column(name = "LastName")
	private String lastName;

	@Column(name = "Age")
	private int age;

	@Column(name = "Education")
	private String education;

	@Column(name = "Salary")
	private int salary;

	public int getEmployeeId() {
		return employeeId;
	}

	public void setEmployeeId(int employeeId) {
		this.employeeId = employeeId;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getEducation() {
		return education;
	}

	public void setEducation(String education) {
		this.education = education;
	}

	public int getSalary() {
		return salary;
	}

	public void setSalary(int salary) {
		this.salary = salary;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("Id:").append(employeeId).append(" FirstName:").append(firstName).append(" 
                                                                       Age:").append(age);
		return sb.toString();
	}
}

We have defined 2 named queries using @NamedQuery and @NamedNativeQuery annotation in the above class.

@NamedQuery is used to define HQL query.

@NamedNativeQuery is used to define Native SQL query.

Step 4

Create Person class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.kb.model;
 
public class Person {
    
    private int personId;
    
    private String firstName;
    
    private String lastName;
    
    private int age;
    
    private String education;
    
    private int salary;
    
    public int getPersonId() {
        return personId;
    }
    public void setPersonId(int personId) {
        this.personId = personId;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getEducation() {
        return education;
    }
    public void setEducation(String education) {
        this.education = education;
    }
    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }
        
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Id:").append(personId).append(" FirstName:").append(firstName).append("  
                                                                                        Age:").append(age);
        return sb.toString();
    }
 
}
package com.kb.model;

public class Person {
	
	private int personId;
	
	private String firstName;
	
	private String lastName;
	
	private int age;
	
	private String education;
	
	private int salary;
	
	public int getPersonId() {
		return personId;
	}
	public void setPersonId(int personId) {
		this.personId = personId;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getEducation() {
		return education;
	}
	public void setEducation(String education) {
		this.education = education;
	}
	public int getSalary() {
		return salary;
	}
	public void setSalary(int salary) {
		this.salary = salary;
	}
		
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("Id:").append(personId).append(" FirstName:").append(firstName).append("  
                                                                                        Age:").append(age);
		return sb.toString();
	}

}

Step 5

Create person.hbm.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?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 package="com.kb.model">
    <class name="Person" table="Person">
        <id name="personId" type="int">
            <column name="Person_Id"></column>
            <generator class="increment"></generator>
        </id>
        <property name="firstName" column="FirstName"></property>
        <property name="lastName" column="LastName"></property>
        <property name="age" type="int" column="Age"></property>
        <property name="education" column="Education"></property>
        <property name="salary" type="int" column="Salary"></property>
    </class>
    <query name="hql_person_select">from Person where age=:age</query>
    <sql-query name="sql_person_select">select * from Person
    </sql-query>
</hibernate-mapping> 
<?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 package="com.kb.model">
	<class name="Person" table="Person">
		<id name="personId" type="int">
			<column name="Person_Id"></column>
			<generator class="increment"></generator>
		</id>
		<property name="firstName" column="FirstName"></property>
		<property name="lastName" column="LastName"></property>
		<property name="age" type="int" column="Age"></property>
		<property name="education" column="Education"></property>
		<property name="salary" type="int" column="Salary"></property>
	</class>
	<query name="hql_person_select">from Person where age=:age</query>
    <sql-query name="sql_person_select">select * from Person
    </sql-query>
</hibernate-mapping> 

We have defined 2 named queries in this mapping file where first one is HQL and second one is Native SQL query.

Step 6

Create hibernate.cfg.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
       "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
       "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
 
    <session-factory>
 
        <!-- Database connection properties -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/javainsimpleway</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
 
        <!-- JDBC connection pool (using the built-in) -->
        <property name="connection.pool_size">100</property>
 
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 
        <!-- Disable the second-level cache -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
 
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">false</property>
 
        <!-- Format the generated Sql -->
        <property name="format_sql">false</property>
 
        <!-- Dont Drop and re-create the database schema on startup,Just update 
            it -->
        <property name="hbm2ddl.auto">update</property>
 
        <mapping class="com.kb.model.Employee" />
        <mapping resource="com/kb/mapping/person.hbm.xml"/>
 
    </session-factory>
 
</hibernate-configuration> 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
       "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
       "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

	<session-factory>

		<!-- Database connection properties -->
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost/javainsimpleway</property>
		<property name="connection.username">root</property>
		<property name="connection.password">root</property>

		<!-- JDBC connection pool (using the built-in) -->
		<property name="connection.pool_size">100</property>

		<!-- SQL dialect -->
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

		<!-- Disable the second-level cache -->
		<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

		<!-- Echo all executed SQL to stdout -->
		<property name="show_sql">false</property>

		<!-- Format the generated Sql -->
		<property name="format_sql">false</property>

		<!-- Dont Drop and re-create the database schema on startup,Just update 
			it -->
		<property name="hbm2ddl.auto">update</property>

		<mapping class="com.kb.model.Employee" />
		<mapping resource="com/kb/mapping/person.hbm.xml"/>

	</session-factory>

</hibernate-configuration> 

We have added both annotation and XML mapping file location in the above config file.

Step 7

Create Hibernate util class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.kb.util;
 
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();
 
    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception to track it
            System.err.println("SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
 
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
    public static void shutdown() {
        // Optional but can be used to Close caches and connection pools
        getSessionFactory().close();
    }
 
}
package com.kb.util;

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

public class HibernateUtil {
	private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception to track it
            System.err.println("SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
    public static void shutdown() {
    	// Optional but can be used to Close caches and connection pools
    	getSessionFactory().close();
    }

}

Step 8

Create PopulateData.java file to Populate Employee Table with initial data

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.kb.db;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
 
import com.kb.model.Employee;
import com.kb.model.Person;
import com.kb.util.HibernateUtil;
 
public class PopulateData {
    public static void main(String[] args) {
 
        // Get session factory using Hibernate Util class
        SessionFactory sf = HibernateUtil.getSessionFactory();
        // Get session from Sesson factory
        Session session = sf.openSession();
 
        // Begin transaction
        Transaction t = session.beginTransaction();
 
        // Create Employee data
        Employee employee1 = new Employee();
        employee1.setFirstName("John");
        employee1.setLastName("KC");
        employee1.setAge(28);
        employee1.setEducation("PG");
        employee1.setSalary(25000);
 
        Employee employee2 = new Employee();
        employee2.setFirstName("Jacob");
        employee2.setLastName("JC");
        employee2.setAge(28);
        employee2.setEducation("PG");
        employee2.setSalary(30000);
 
        Employee employee3 = new Employee();
        employee3.setFirstName("Martin");
        employee3.setLastName("A");
        employee3.setAge(24);
        employee3.setEducation("UG");
        employee3.setSalary(20000);
 
 
        // Create Person data
 
        Person Person1 = new Person();
        Person1.setFirstName("Peter");
        Person1.setLastName("M");
        Person1.setAge(28);
        Person1.setEducation("UG");
        Person1.setSalary(22000);
 
        Person Person2 = new Person();
        Person2.setFirstName("Roshan");
        Person2.setLastName("B");
        Person2.setAge(28);
        Person2.setEducation("PG");
        Person2.setSalary(45000);
 
        session.save(employee1);
        session.save(employee2);
        session.save(employee3);
        session.save(Person1);
        session.save(Person2);
 
        // Commit the transaction and close the session
        t.commit();
 
        session.close();
        System.out.println("successfully persisted Employee and Person details");
 
    }
} 
package com.kb.db;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.kb.model.Employee;
import com.kb.model.Person;
import com.kb.util.HibernateUtil;

public class PopulateData {
	public static void main(String[] args) {

		// Get session factory using Hibernate Util class
		SessionFactory sf = HibernateUtil.getSessionFactory();
		// Get session from Sesson factory
		Session session = sf.openSession();

		// Begin transaction
		Transaction t = session.beginTransaction();

		// Create Employee data
		Employee employee1 = new Employee();
		employee1.setFirstName("John");
		employee1.setLastName("KC");
		employee1.setAge(28);
		employee1.setEducation("PG");
		employee1.setSalary(25000);

		Employee employee2 = new Employee();
		employee2.setFirstName("Jacob");
		employee2.setLastName("JC");
		employee2.setAge(28);
		employee2.setEducation("PG");
		employee2.setSalary(30000);

		Employee employee3 = new Employee();
		employee3.setFirstName("Martin");
		employee3.setLastName("A");
		employee3.setAge(24);
		employee3.setEducation("UG");
		employee3.setSalary(20000);


		// Create Person data

		Person Person1 = new Person();
		Person1.setFirstName("Peter");
		Person1.setLastName("M");
		Person1.setAge(28);
		Person1.setEducation("UG");
		Person1.setSalary(22000);

		Person Person2 = new Person();
		Person2.setFirstName("Roshan");
		Person2.setLastName("B");
		Person2.setAge(28);
		Person2.setEducation("PG");
		Person2.setSalary(45000);

		session.save(employee1);
		session.save(employee2);
		session.save(employee3);
		session.save(Person1);
		session.save(Person2);

		// Commit the transaction and close the session
		t.commit();

		session.close();
		System.out.println("successfully persisted Employee and Person details");

	}
} 


We are persisting 3 employees and 2 person records in the above class.

Step 9

Lets Create Main class to access Named queries

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.kb.db;
 
import java.util.Iterator;
import java.util.List;
 
import javax.persistence.Query;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
 
import com.kb.model.Employee;
import com.kb.model.Person;
import com.kb.util.HibernateUtil;
 
public class NamedQuery {
    @SuppressWarnings("deprecation")
    public static void main(String[] args) {
        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session session = sf.openSession();
 
        //Named query from Annotation mapping
        Query queryHqlEmpSelect = session.getNamedQuery("hql_employee_select");
        queryHqlEmpSelect.setParameter("age", 28);
        List<Employee> empList = queryHqlEmpSelect.getResultList();
        System.out.println("HQL-Number of Employees present with Age 28--> " + empList.size());
        System.out.println("HQL-Employees retrieved");
        for (Employee employee : empList) {
            System.out.println(employee);
        }
 
        Query querySqlEmpSelect = session.getNamedQuery("sql_employee_select");
        List empListSql = querySqlEmpSelect.getResultList();
        System.out.println("SQL-Number of Employees present--> " + empListSql.size());
        System.out.println("SQL-Employees retrieved");
        
            Iterator iterator1 = empListSql.iterator();
            while (iterator1.hasNext()) {
                Object[] object = (Object[]) iterator1.next();
                System.out.println("EmployeeId : " + object[0] + " Age : " + object[1]
                        + " Education : " + object[2]);
            }
            
                 /* for (Employee employee : empList) {
            System.out.println(employee);
              }*/
 
        //Named query from XML mapping
        Query queryHqlPersonSelect = session.getNamedQuery("hql_person_select");
        queryHqlPersonSelect.setParameter("age", 28);
        List<Person> personList = queryHqlPersonSelect.getResultList();
        System.out.println("HQL-Number of Persons present with Age 28--> " + personList.size());
        System.out.println("HQL-Persons retrieved");
        for (Person person : personList) {
            System.out.println(person);
        }
 
        Query querySqlPersonSelect = session.getNamedQuery("sql_person_select");
        personList = querySqlPersonSelect.getResultList();
        System.out.println("SQL-Number of Persons present--> " + personList.size());
        System.out.println("SQL-Persons retrieved");
            Iterator iterator2 = personList.iterator();
            while (iterator2.hasNext()) {
                Object[] object = (Object[]) iterator2.next();
                System.out.println("PersonId : " + object[0] + " Age : " + object[3]
                        + " Education : " + object[4]);
            }
        session.close();
    }
 
}
package com.kb.db;

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

import javax.persistence.Query;

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

import com.kb.model.Employee;
import com.kb.model.Person;
import com.kb.util.HibernateUtil;

public class NamedQuery {
	@SuppressWarnings("deprecation")
	public static void main(String[] args) {
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();

		//Named query from Annotation mapping
		Query queryHqlEmpSelect = session.getNamedQuery("hql_employee_select");
		queryHqlEmpSelect.setParameter("age", 28);
		List<Employee> empList = queryHqlEmpSelect.getResultList();
		System.out.println("HQL-Number of Employees present with Age 28--> " + empList.size());
		System.out.println("HQL-Employees retrieved");
		for (Employee employee : empList) {
			System.out.println(employee);
		}

		Query querySqlEmpSelect = session.getNamedQuery("sql_employee_select");
		List empListSql = querySqlEmpSelect.getResultList();
		System.out.println("SQL-Number of Employees present--> " + empListSql.size());
		System.out.println("SQL-Employees retrieved");
		
	        Iterator iterator1 = empListSql.iterator();
	        while (iterator1.hasNext()) {
	            Object[] object = (Object[]) iterator1.next();
	            System.out.println("EmployeeId : " + object[0] + " Age : " + object[1]
	                    + " Education : " + object[2]);
	        }
	        
	             /*	for (Employee employee : empList) {
			System.out.println(employee);
		      }*/

		//Named query from XML mapping
		Query queryHqlPersonSelect = session.getNamedQuery("hql_person_select");
		queryHqlPersonSelect.setParameter("age", 28);
		List<Person> personList = queryHqlPersonSelect.getResultList();
		System.out.println("HQL-Number of Persons present with Age 28--> " + personList.size());
		System.out.println("HQL-Persons retrieved");
		for (Person person : personList) {
			System.out.println(person);
		}

		Query querySqlPersonSelect = session.getNamedQuery("sql_person_select");
		personList = querySqlPersonSelect.getResultList();
		System.out.println("SQL-Number of Persons present--> " + personList.size());
		System.out.println("SQL-Persons retrieved");
	        Iterator iterator2 = personList.iterator();
	        while (iterator2.hasNext()) {
	            Object[] object = (Object[]) iterator2.next();
	            System.out.println("PersonId : " + object[0] + " Age : " + object[3]
	                    + " Education : " + object[4]);
	        }
		session.close();
	}

}


We have accessed HQL and SQL queries defined in both Annotation and XML mapping and executing those queries in the above class.

Step 10

Run PopulateData.java class to create the initial data

Check an output in MYSQL DB

E:\MySql_Install\bin
Mysql –u root –p
Enter password

Use javainsimpleway;

Select * from Employee;

Select * from Person;

named_query_output1

We can see that Emploeyee table has 3 records and Person table has 2 records

Step 11

Run the main class NamedQuery.java to check the output of Named queries

Output

We can see that both Person and Employee records are retrieved using HQL and SQL Named queries.

Download this project NamedQuery.zip

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on