Hibernate Named Query using Annotation

Facebooktwitterredditpinterestlinkedinmailby feather

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.

  • Create a POJO class

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

Student.java

  • Create the configuration file.

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

hibernate.cfg.xml

  • 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

OUTPUT

Database table

Facebooktwitterredditpinterestlinkedinmailby feather