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 two are optional. The two required attributes are name and query which defines the query name and the query string itself. The two optional attributes are lockMode and hints which provide the replacement for setLockMode() and setHint() methods.

Example of Named Query using annotation

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

In this example, we are going to fetch an existing record using Named query. Following are the steps to create an example of a Named query using annotation.

  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

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.NamedQuery;
  
@Entity
@NamedQuery(name= "Student.byId", query="from Student where Sid=?0") 
@Table(name="students")
public class Student {
  
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="Sid")
private int id;
             
@Column(name="S_name")
private String name;
             
@Column(name="S_rno")
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 the configuration file.

The configuration file contains the information of mapping classes and database.

hibernate.cfg.xml




  

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

  • 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(0, 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 History and Versions

Next → History of Hibernate Hibernate was developed in 2001 by Gavin king with his colleagues from Circus Technologies. The main aim was to provide better persistence capabilities than those of EJB2, by reducing the...

2 minutes read.

Hibernate One-to-One Mapping Example

One-to-One Hibernate Mapping In One-to-One association mapping, one object of a persistent class is related to one object of another persistent class. Here, we are going to create an example of one-to-one mapping using...

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.

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 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 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 Many-to-Many Mapping

Many-to-Many Hibernate Mapping with Example In Many-to-Many association mapping, more than one objects of a persistent class are associated with more than one objects of another persistent class. For example, many (categories) are related to...

3 minutes read.

Hibernate Composite Primary Key

Hibernate Composite Primary Key A Composite Primary Key is a combination of one or more columns that forms a primary key. When a database table contains more than one primary key column, it is...

8 minutes read.

Hibernate SessionFactory

Next → Hibernate SessionFactory A SessionFactory is an interface in Hibernate that create the instances of Session interface. It is a heavy weight object, and it is usually created during the application...

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 Mapping

Hibernate Mapping Association- It means that two or more things are related to each other by some specific relation. In other words, it specifies how the objects are associated with each other. Hibernate mapping is one...

2 minutes read.

Hibernate merge() vs. update()

In Hibernate, both update() and merge() methods are used to convert the detached state object into the persistent state. session.merge() The merge() method is used when we want to change a detached entity into...

2 minutes read.

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.

Dirty Checking in Hibernate

Dirty checking is an essential concept of Hibernate. The Dirty checking concept is used to keep track of the objects. It automatically detects whether an object is modified (or not) or wants to...

6 minutes read.

Hibernate Session Interface

Hibernate Session Interface A Session is an interface between the Java application and the Hibernate. It is available in the org.hibernate.session package. It should not be kept open for a long time, as it...

4 minutes read.

Hibernate Web Application Example

Web Application Example with Hibernate In this section, we create a hibernate web Application. Here we are using a JSP file for presentation. Example of creating a web application using hibernate index.jsp This page will show a...

2 minutes read.

Hibernate vs. JPA

What is JPA? JPA stands for Java Persistence API, which defines a set of functionalities, standards, and concepts to the ORM tool. It is a framework used to manage relational databases. It is available...

2 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 Query Language (HQL)

Hibernate provides its query language called Hibernate Query Language (HQL). HQL is an object-oriented query language, similar to the native SQL language, and it works with persistent objects. It is a database-independent and...

2 minutes read.

Hibernate Second-Level Cache

The Second-level cache is related to the SessionFactory object. Once the SessionFactory is closed, all the second-level cache data associated with it will be lost. The cache manager will also get closed. Cache provider The...

5 minutes read.