Updated April 10, 2023
Introduction to Hibernate Named Query
Hibernate named query is a way to define queries with a specific keyword. This keyword is then used throughout the project to avoid the confusion of writing query repetitively. This makes sure that the code is mess free and has lower maintenance efforts. This feature can be used in HQL(Hibernate query language) or native SQL. It is a way to provide an alias to the query statement. There are two ways of to define named query which are explained in below sections.
Working of Hibernate Named Query
The working of HQN can be best understood via an example provided below:
Code:
//This is the entity declarations which are important for any query to run:
Name: employeedetails.java
package com.EduCBA;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class TestEmp {
@Id
@GeneratedValue()
private double idnumber;
private String empNum;
}
//Below is the code snippet depicting the usage of the named query in the Java program of the project. This is the continuation of previous code.
@org.hibernate.annotations.NamedQuery(name = "TestNamedQuery",
query = "from TestEmp where empNum= :employeeNumber")
//Below id the config file for mapping purposes.
Name: testhiber.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping class="com.EduCBA.TestEmp "/>
</session-factory>
</hibernate-configuration>
//Below is the use of named query created above.
Name:UsageofQuery.java
import java.util.*;
import javax.persistence.*;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.*
public class FetchingResults {
public static void main(String[] args) {
StandardServiceRegistry testssr = new StandardServiceRegistryBuilder().configure("hibertest.cfg.xml").build();
Metadata m = new MetadataSources(testssr).getMetadataBuilder().build();
SessionFactory sessfact=m.getSessionFactoryBuilder().build();
Session sess = sessfact.openSession();
TypedQuery testquery = sess.getNamedQuery("TestNamedQuery");
testquery.setParameter("Id","123");
List<TestEmp> employees= testquery.getResultList();
Iterator<TestEmp> i = TestEmp.iterator();
while (i.hasNext()){
TestEmp emp = i.next();
System.out.println(emp);} session.close(); }}
Also please install all the related libraries and modules as mentioned below. Maven library should be there to build a project.
Explanation: The named query works when we have annotation or mapping file loaded with named annotation/ mapping via the query tab. This should contain primarily two things. One is the “name” of query which should be used as a reference to call this query while the other one is “query” where the query is written. These two are mandatory declarations so as to assign a query to the name.
Ways of Hibernate Named Query
Different ways to define Hibernate Named Query:
HNQ (Hibernate named query) is a way of assigning a query string to a variable. This variable can be then be used throughout the project as per the requirements. There are mainly two ways of defining HNQ:
1. Annotation
There are two annotations (@keyword) under JPA (Java persistence API) used to create named queries. These are some annotations used-
- @NAMEDQUERY: This annotation is used to generate a new keyword that can be assigned to the query string. There are some syntax rules to be followed to use it efficiently. HQL named query uses query element in hibernate XML file (ex: namequeries.hbm.xml).
Below is the example:
Code:
@NamedQuery
(
name="UsingNamedAnnotation",
query="from student stu where stu.name=:name"
)
- @NAMEDNATIVEQUERY: This annotation is used in SQL named queries. SQL named query uses native sql query element in hibernate xml file(ex:namedqueries.hbm.xml).
Below is the example:
Code:
@NamedNativeQueries
(
@NamedNativeQuery
(
name="UsingNamedNativeAnnotation",
query="from school sch where sch.name=:name"
)
)
- @NAMEDQUERIES: This annotation is used when we generate more than one named query under a named notation. This enables the definition of multiple named queries simultaneously in one place.
Below is the example:
@NamedQueries
(
@NamedQuery
(
name="UsingNamedAnnotation1",
query="from student stu where stu.name=:name"
)
@NamedQuery
(
name="UsingNamedAnnotation2",
query="from teacher tr where tr.name=:name"
)
)
2. Mapping File
One can directly define named queries in the mapping file via the query tag. This reduces the need to produce annotations, hibernate configuration files, and mapping resources to hbm file. The extension to be used after file name for the file containing mapping is “.hbm.xml” and along with this “test.java” file should be with relevant configuration files.
Below is the example:
Code:
<query name="UsingNamedAnnotation">
<![CDATA[from test t where t.name= :name]]>
</query>
Advantages of Hibernate Named Query
Some of the advantages of HQN are listed below:
- It avoids the code mess. There are some standard extraction or update queries that are used repetitively in the project increasing the code lines and creating confusion while maintenance. This functionality of naming the query statement reduces the code lines and improves the look and feel of code. This results in a reduction of maintenance hours and charges.
- The syntax of HQN is checked when the first instance of the hibernate session factory is initiated, because of this the syntax check is done in the initial phase for once and in case if the syntax is not up the defines structure then an error is thrown immediately. This makes the application fast and error-proof.
- In case we have a syntax problem in the query, it can be corrected in one place where it is assigned to named annotation. This reduces the probability of query syntax related errors.
- HQN is defined as global. That means once HQN defines it can be used throughout an application. This reduces the coding efforts and reduces the chances of errors.
Conclusion
HQN is a very effective tool used widely by coders out there. When it comes to writing effective and maintenance-friendly code then JAVA developers look forward to naming annotations. It propagates the rapid development of an application thereby cutting the time used for project delivery. This is used in HQL and native SQL linked projects extensively. It is strongly recommended to use named queries when the project is big.
Recommended Articles
This is a guide to Hibernate Named Query. Here we discuss the Introduction and Working of Hibernate Named Query and its different ways along with its advantages. You can also go through our other suggested articles to learn more –