EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Hibernate Named Query

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » Hibernate Tutorial » Hibernate Named Query

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 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:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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

Popular Course in this category
Hibernate course (4 Courses, 4 Projects)4 Online Courses | 4 Hands-on Project | 32+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (3,305 ratings)
Course Price

View Course

Related Courses

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

Note: These are the code snippets to understand the named query syntax. Please follow the general guidelines to have them in your hibernate code. There are multiple other files that need to be created to have the project implemented. Please make sure that the name of files along with extension are properly maintained. The same can be done via a mapping file instead of annotation with the help of query function.
Hibernate Named Query 1

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:

  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 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 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.
  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.

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 –

  1. Cascade in Hibernate (Examples)
  2. Top 6 Hibernate Versions
  3. What is Hibernate Framework?
  4. 10 Best Hibernate Interview Questions
  5. Hibernate Tools | Top 12
  6. Guide to Hibernate Many to Many

Hibernate course (4 Courses, 4 Projects)

4 Online Courses

4 Hands-on Project

32+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

1 Shares
Share
Tweet
Share
Primary Sidebar
Hibernate Tutorial
  • Basic
    • What is Hibernate
    • What is Java Hibernate
    • Hibernate Versions
    • Hibernate Architecture
    • Hibernate Framework
    • Hibernate Tools
    • Hibernate Annotations
    • Hibernate Mapping
    • Hibernate Many to One
    • Hibernate Many to Many
    • Hibernate Dialect
    • Hibernate Session
    • Hibernate SessionFactory
    • Lazy Loading in Hibernate
    • Hibernate Criteria
    • Hibernate Persist
    • Hibernate EntityManager
    • Caching in Hibernate
    • Cascade in Hibernate
    • Hibernate Generator
    • Hibernate Validator
    • Spring Hibernate Integration
    • Hibernate Query Language
    • Hibernate Named Query
    • Hibernate Interview Questions
    • HQL
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - Hibernate course (4 Courses, 4 Projects) Learn More