• If we are using HQL or Native SQL queries multiple time then it will be code mess because all queries will be scattered throughout the project.
  • Hibernate Named Query is a way to use queries by giving a name.
  • Hibernate Named Queries will be defined at one place and used anywhere in the project.
  • use of named query in hibernate
  • Writing HQL query in HBM file is called HQL Named Query.
  • Or we can use @NameQuery annotation in entity.
  • For writing Hibernate Named Queries we will use <query> tag in Hibernate mapping file Or @NameQuery annotation in the entity.
  • If we want to create Named Query using hibernate mapping file then we need to use query element.



Advantages of Named Query in Hibernate 

  • Global access
  • Easy to maintain.

Hibernate Named Queries by using Annotations:

  • If we want to create Named Queries using annotations in entity class then we need to use @NameQueries and @NameQuery annotations
  • @NameQuery will be used to create single Query
  • @NameQueries annotations will be used to create multiple Queries. When we are using @NameQueries for every query we need to use @NameQuery annotation.

Hibernate Named Query example by using Annotations:


Hibernate Named Query example join

  1. Query query = session.getNamedQuery("findDocterById");
  2.         query.setInteger("id", 37);
  3.        List empList = query.list();


Hibernate Named Queries by using Hibernate mapping file:

  • We need to configure Hibernate Named Queries as part of Hibernate mapping file.
  • By using <query> element we need to write Hibernate named Queries.

  1. <hibernate_mapping>
  2.             <class  >
  3.             ---------
  4.             </class>
  5.  
  6.  <query name = “findDocterById”>
  7.  <![CDATA[from Docter s where s.id = :id]]>
  8. </query>  

  9.  </hibernate_mapping>     


  1. Query query = session.getNamedQuery("findDocterById");
  2.         query.setInteger("id", 64);
  3.        List empList = query.list();

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu