Hibernate Named Query Using XML

A named query is a technique used to assemble all the queries (Native SQL and HQL) in a specific location and refer them by some name. It helps in reducing the mess created by the queries scattered in all the java codes.

Named queries are verified when the SessionFactory is created. It makes the application to fail fast in case of an error. Named queries are global to access, which means they can be used throughout the application once defined. The named query is given a unique name for the entire application. In this way, the application uses the same query multiple times without re-writing the same query. Hence, the main advantages of the named query are failing fast and re-usability.

In the case of performance, a named query does not make much difference.

Example of Named Query using XML

Here, we are going to create an example of a named query using a mapping file. In the mapping file, we are using the element <query>…</query> to define the named query.

Let us assume a table (students) containing three columns (Sid, S_name, and S_rno) are present in the database.

Following are the steps to create an example of Named Query using XML.

  1. Add Dependencies

For this example, you need to add some dependencies in pom.xml.

 
org.hibernate
hibernate-core
5.4.0.Final


mysql
mysql-connector-java
8.0.16
 
  • Create a POJO class

In this step, we are going to create a POJO class, i.e., Student.java.

Student.java

public class Student {
private int id;
private String name;
private int rollno;
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 getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}                  
} 
  • Create a mapping file for the POJO class.

In this step, we are going to create a mapping file for the POJO class, i.e., student.hbm.xml file in which we define <query>…</query> element.

student.hbm.xml

  
  
  
  



 

  
  
  
  
  
  • Create the configuration file.

In this step, we are going to add the entry of the mapping file (student.hbm.xml) in the configuration file (hibernate.cfg.xml).

hibernate.cfg.xml





org.hibernate.
dialect.MySQL5Dialect
com.mysql.
jdbc.Driver
jdbc:mysql:
//localhost:3306/test2
root
root
update   
true 
   

   

 
  • Create the main class that stores the object of POJO class.

In this step, we are going to create a main class (which contains the main method) that stores the object of the POJO class.

App.java

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class App 
{
public static void main( String[] args )
{
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory= cfg.buildSessionFactory();
Session session=factory.openSession();
session.beginTransaction();
Query query=session.getNamedQuery("Student.byId");
query.setInteger("Sid", 2);
List std= (List) query.list();
session.getTransaction().commit();
session.close();
for(Student student : std)
{
System.out.println(student.getName());
}
System.out.println("successfull");
}
} 

OUTPUT

Database Table


Related Topics

Hibernate Dialects

Hibernate Dialects Dialect is a Java class available in org.hibernate.dialect package, which helps to map Java Application with the database. To interact with the database, we need to define the required database dialect in...

2 minutes read.

Hibernate vs. JDBC

What is Hibernate? Hibernate is an Object-Relational Mapping (ORM) tool which reduces the difficulty in the application development. Hibernate provides a framework that interacts with the data stored in the databases. It also uses...

2 minutes read.

Hibernate Named Query Using XML

A named query is a technique used to assemble all the queries (Native SQL and HQL) in a specific location and refer them by some name. It helps in reducing the mess...

3 minutes read.

Hibernate N+1 Select Problem

Hibernate N + 1 Select Problem The N + 1 Select problem is a performance issue in Hibernate. In this problem, a Java application makes N + 1 database calls (N = number...

4 minutes read.

Hibernate GeneratedValue Strategies

Hibernate GeneratedValue Strategies Hibernate supports some generation strategies to generate a primary key in the database table. We can access the strategy with the help of @GeneratedValue annotation. @GeneratedValue The @GeneratedValue annotation specifies how to...

3 minutes read.

Hibernate Configuration Properties

Hibernate Configuration Hibernate Configuration is a Java class, which allows a Java application to specify configuration parameters used in the application. As Hibernate is designed to serve in different environments, it needs a broad...

6 minutes read.

Hibernate save() vs persist()

Session.save() The session.save() method is used to save the transient object by assigning a generated value or using a current value of the identifier property. In other words, the save() method is used...

3 minutes read.

Hibernate first Example

Now we are going to create the first example in Hibernate. We will proceed step by step to develop the first Java application in Hibernate. The steps are listed below:- Create the POJO...

2 minutes read.

Hibernate Lifecycle

Hibernate Lifecycle In Hibernate, the mapped instances of the entity classes have a lifecycle. Either we can create a new object, or we can fetch the existing data from the database. The value objects do...

3 minutes read.

Hibernate Named Query using Annotation

In annotation-based named query, we use @NamedQuery annotation inside the POJO class. @NamedQuery- It is used to describe a single named query. It consists of four attributes- two of which are compulsory, and...

2 minutes read.

Hibernate Tutorial

What is Hibernate? Hibernate is an Object-Relational Mapping (ORM) tool which reduces the difficulty in the application development. Hibernate provides a framework that interacts with the data stored in the databases. It also uses...

3 minutes read.

Hibernate One-to-Many Mapping

One-to-Many Hibernate Mapping Example In One-to-many association mapping, only one object of a persistent class is related to many objects of another persistent class. It is a relationship in which one (parent) is related...

3 minutes read.

Annotation Example in Hibernate

Hibernate Annotation Example Hibernate is an ORM (Object-Relational Mapping) tool which simplifies the application development. Hibernate provides a framework which interacts with the data stored in the databases, and it also uses...

3 minutes read.

Hibernate First-Level Cache

The first-level cache is related to the Session object. First level cache objects of one Session are not visible to the other Sessions, and all the cache data is lost when the Session...

2 minutes read.

Hibernate get() vs. load()

Hibernate methods, get() and load() both are provided by the Session interface and used to retrieve the objects from the database. Session.get() The session.get() method is used to fetch a persistent object of the...

2 minutes read.

Hibernate Inheritance Joined Table

In this inheritance strategy, mapping of the child class fields is done with the common fields of the parent class in a separate table. In other words, the common entities between the child...

3 minutes read.

Hibernate Many-to-One Mapping

Many-to-One Hibernate Mapping with Example A Many-to-One association mapping is the reverse of One-to-Many association mapping. For example, many (customers) are associated with one (vendor). In Hibernate, Many-to-One association mapping is applied from child class...

3 minutes read.

Cascade in Hibernate

Cascading is a feature in Hibernate, which is used to manage the state of the mapped entity whenever the state of its relationship owner (superclass) affected. When the relationship owner (superclass) is saved/...

3 minutes read.

Hibernate Inverse

Hibernate Inverse An Inverse attribute is used to maintain the relationship between the parent and child class object. The inverse attribute is used only with bi-directional mappings such as one-to-many and many-to-many Hibernate mapping. In Hibernate, the...

2 minutes read.

Lazy Loading in Hibernate

Lazy loading is a fetching technique used for all the entities in Hibernate. It decides whether to load a child class object while loading the parent class object. When we use association mapping...

3 minutes read.