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 Criteria Query Language (HCQL)

Hibernate Criteria Query Language (HCQL) is mainly used for searching and fetching records. It works on the filtration rules and logical conditions. The Criteria interface, Restriction class, and Order class are available in...

4 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 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 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 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 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 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 Web Application with Example

Let us create a hibernate web Application. Here we need JSP file for presentation. There are steps given below for the web app creation. index.jsp This page will show a registration form. It takes the...

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 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 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.

Hibernate Inheritance - Single Table

Hibernate Inheritance In this inheritance strategy, only one table is created for all the classes involved in the hierarchy with an additional column known as a discriminator column. The discriminator column helps indifferentiating between...

3 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 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.

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.

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.

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 Inheritance Table Per Class

In this inheritance strategy, table per class is generated. It means a separate table is generated for each POJO class involved in the hierarchy. Unlike the SINGLE_TABLE strategy, there are no nullable values...

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 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.