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.

  • Create a POJO class

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

Student.java

  • 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

  • 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

Pin It on Pinterest

Share This