Works and ways of Hibernate Named Query

Works and ways of Hibernate Named Query
Techiio-author
Written by Sagar RabidasFebruary 17, 2022
8 min read
Hibernate
2 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 2 VIEWS SHARE
Techiio-author
Sagar Rabidas

Software Developer

Let's start the discussion with Hibernate Named Query

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 queries 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 defining a named query which is explained 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 that 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 the previous code.

@org.hibernate.annotations.NamedQuery(name = "TestNamedQuery",
query = "from TestEmp where empNum= :employeeNumber")

//Below is 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 the 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(); }}

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:

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”
)
)

Mapping File:-

You will immediately define named queries in the mapping file thru the query tag. This reduces the want to produce annotations, hibernate configuration files, and map assets to HBM files. The extension to be used after the file called for the report containing mapping is “.Hbm.Xml” and along with this “test.Java” report must be with relevant configuration documents.

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:

  1. 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 the code. This results in a reduction of maintenance hours and charges.
  2. 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 once and in case the syntax is not up the defined structure then an error is thrown immediately. This makes the application fast and error-proof.
  3. 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.
  4. 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.

Hibernate
Hibernate Named
Named Query
Java
2 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 2 VIEWS SHARE
Was this blog helpful?
techiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plan
You must be Logged in to comment
Code Block
Techiio-author
Sagar Rabidas
Software Developer
Techiio-followerTechiio-followerTechiio-followerTechiio-followerTechiio-follower
+9 more
300 Blog Posts
14 Discussion Threads
Trending Technologies
15
Software40
DevOps48
Frontend Development24
Backend Development20
Server Administration17
Linux Administration26
Data Center24
Sentry24
Terraform23
Ansible83
Docker70
Penetration Testing16
Kubernetes21
NGINX20
JenkinsX17
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance