Home » Hibernate Named Query Example

Hibernate Named Query Example

by Online Tutorials Library

Hibernate Named Query

The hibernate named query is way to use any query by some meaningful name. It is like using alias names. The Hibernate framework provides the concept of named queries so that application programmer need not to scatter queries to all the java code.

There are two ways to define the named query in hibernate:

  • by annotation
  • by mapping file.

Hibernate Named Query by annotation

If you want to use named query in hibernate, you need to have knowledge of @NamedQueries and @NamedQuery annotations.

@NameQueries annotation is used to define the multiple named queries.

@NameQuery annotation is used to define the single named query.

Let’s see the example of using the named queries:


Example of Hibernate Named Query by annotation

In this example, we are using annotations to defined the named query in the persistent class. There are three files only:

  • Employee.java
  • hibernate.cfg.xml
  • FetchDemo

In this example, we are assuming that there is em table in the database containing 4 columns id, name, job and salary and there are some records in this table.

Employee.java

It is a persistent class that uses annotations to define named query and marks this class as entity.


hibernate.cfg.xml

It is a configuration file that stores the informations about database such as driver class, url, username, password and mapping class etc.


FetchData.java

It is a java class that uses the named query and prints the informations based on the query. The getNamedQuery method uses the named query and returns the instance of Query.

Hibernate Named Query by mapping file

If want to define named query by mapping file, you need to use query element of hibernate-mapping to define the named query.

In such case, you need to create hbm file that defines the named query. Other resources are same as given in the above example except Persistent class Employee.java where you don’t need to use any annotation and hibernate.cfg.xml file where you need to specify mapping resource of the hbm file.

The hbm file should be like this:

emp.hbm.xml


The persistent class should be like this:

Employee.java


Now include the mapping resource in the hbm file as:

hibernate.cfg.xml

You may also like