What is Hibernate Named Query

In this article, we will see What is named query in Hibernate and why we need it even though we have already seen so many ways in which we can retrieve data from the database such as by using HQL, HCQL, and also Native SQL.

What is Named Query?

Named Query is the way to group all the query statements in one place that would have global access throughout the code and we can refer to the query using the name specified.

  • It helps in code organization through which we separate the code with a query string.
  • It helps in code reusability.
  • Named Query is declared as Global so that we can use the query all over the code.

Syntax:

Named Query can be defined in Hibernate using Annotation and using Mapping File.

@NamedQueries(
    {
      @NamedQuery(
                   name ="byName",
                   query = "from Student"
                 )
      
    }
    
)
  • @NamedQueries annotation is used to attach multiple queries to the same Entity class. 
  • @NamedQuery annotation includes the query which you want to run. It has the following attributes.
    • name: This defines the alias name to the query.
    • query: This attribute defines the query.
    • lockMode & hints which are not compulsory attributes.
  • The name attribute of @NamedQuery annotation should be unique.

Example of Hibernate Named Query

Let us first create a configuration file hibernate.cfg.xml file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/college</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <mapping class="com.abc.Student" />
  </session-factory>
</hibernate-configuration>

Now Create a java Class/Entity  Student for setting and getting data. We are creating annotated-based classes so we won’t need a mapping file now. (for annotation you can see the previous article How to use Annotation in Hibernate?).

  • Here, we have used @NamedQueries annotation & @NamedQuery Annotation with the name attribute and query attribute.
  • Using this, it will retrieve all the Student object from the database.

Student.java

package com.abc;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

@NamedQueries(
    {
      @NamedQuery(
          name ="byName", //alias for the query
          query = "from Student" //query to run
          )
      
    }
    
)

@Entity // specifies that class in an entity
@Table(name = "student") // defines the table
public class Student {

  @Id // indicate it is a primary key of the table.
  @GeneratedValue(strategy = GenerationType.IDENTITY) // annotation is to
                            // configure the way of
                            // increment of the
                            // specified
                            // column(field).
  @Column(name = "id")
  private int id;

  @Column(name = "name")
  private String nameOfStudent;

  @Column(name = "address")
  private String add;

  @Column(name = "collegename")
  private String cn;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getNameOfStudent() {
    return nameOfStudent;
  }

  public void setNameOfStudent(String nameOfStudent) {
    this.nameOfStudent = nameOfStudent;
  }

  public String getAdd() {
    return add;
  }

  public void setAdd(String add) {
    this.add = add;
  }

  public String getCn() {
    return cn;
  }

  public void setCn(String cn) {
    this.cn = cn;
  }

  public Student() {
    super();
  }

}

Now, create the main class Test.java

In this class, we have used the Query Interface method getNamedQuery() method passed with the name parameter that we have used in the Entity class  @NamedQuery annotation. The query returns the Object in List form so we have to use List Object from java. util package and we have displayed the data using for loop. (Let’s consider we have some data in our created table).

package com.abc;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test {

  public static void main(String[] args) {
      SessionFactory factory = new Configuration().configure().buildSessionFactory();
        Session session = factory.openSession();
        session.beginTransaction();
       
       /* Let's see the named Query query*/
        Query q=session.getNamedQuery("byName");
        List<Student> studList=q.list();
        for(Student e:studList)
        {
          System.out.println(e.getId()+" "+e.getNameOfStudent()+" "+e.getCn());
        }
        session.getTransaction().commit();
       // System.out.println("table craeted");
  }
}

OUTPUT:

1 Harry hogwarts
2 Ron hogwarts
3 Hermoine hogwarts

we can define multiple queries inside the @NamedQuery Annotation for the Entity class like this:

@NamedQueries(
    {
      @NamedQuery(
          name ="byName", //alias for the query
          query = "from Student" //query to run
          ),
                        @NamedQuery(
          name ="searchbyName", //alias for the query
          query = "from Student s Where s.name =: name" //query to run
          ),
      
    }
    
)

Advantages of Named Query in Hibernate

  • This query in Hibernate helps us to collect all the queries in a single place instead of writing queries all over the program.
  • It helps us to reuse the code.
  • The application just uses the name of the query specified globally to perform operations.

Thus, this was all about Named Query in Hibernate. In the next article of this tutorial, we will see how to do catching in Hibernate.