- 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:
- Query query = session.getNamedQuery("findDocterById");
- query.setInteger("id", 37);
- 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.
- <hibernate_mapping>
- <class >
- ---------
- </class>
- <query name = “findDocterById”>
- <![CDATA[from Docter s where s.id = :id]]>
- </query>
- </hibernate_mapping>
- Query query = session.getNamedQuery("findDocterById");
- query.setInteger("id", 64);
- List empList = query.list();
No comments