Named Queries help in removing queries from the code and add in the mapping file or the entity.
@NamedQuery
For creating a named query, we can use the @NamedQuery annotation. The @NamedQuery annotation accepts a name and the query.
Named Query Example
This example creates a Named query called “getEmployees” that fetches Employee details.
Here is the corresponding employee table :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | package com.topjavatutorial; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQuery; import org.hibernate.annotations.Formula; @NamedQuery(name="getEmployees",query="from Employee") @Entity public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; @Column private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString() { return "Employee{id = " + getId() + ", name = " + getName() + ", age = " + getAge() + "}"; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | package com.topjavatutorial; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; public class NamedQueryDemo { public static void main(String[] args) { SessionFactory factory = HibernateUtil.getSessionFactory(); Session session = factory.openSession(); Query query = session.getNamedQuery("getEmployees"); List employees = query.list(); System.out.println(employees); session.close(); } } |
Output:
Hibernate:
select
employee0_.id as id1_0_,
employee0_.age as age2_0_,
employee0_.name as name3_0_,
UPPER(employee0_.name) as formula0_
from
Employee employee0_
[Employee{id = 1, name = John, age = 21}, Employee{id = 2, name = Dave, age = 31}, Employee{id = 3, name = Joy, age = 41}]
Similar to defining Named query in Entity class, we can define it in the mapping file as well.
@NamedQueries
We can use @NamedQueries to define multiple NamedQueries.
Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | @NamedQueries({ @NamedQuery(name = "getEmployeesByName", query = "from Employee where name= :name"), @NamedQuery(name = "getEmployeesById", query = "from Employee where id= :id") }) @Entity public class Employee { // fields and getters/setters } |
© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post