Hibernate Named Query

Hibernate Named Query

Hibernate Named Query

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:

  1. @NamedQueries(  
  2.     {  
  3.         @NamedQuery(  
  4.         name = "findEmployeeByName",  
  5.         query = "from Employee e where e.name = :name"  
  6.         )  
  7.     }  
  8. )  

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

  1. package com.tpoint;  
  2.   
  3. import javax.persistence.*;  
  4. import javax.persistence.Entity;  
  5. import javax.persistence.GeneratedValue;  
  6. import javax.persistence.Id;  
  7.   
  8. @NamedQueries(  
  9.     {  
  10.         @NamedQuery(  
  11.         name = "findEmployeeByName",  
  12.         query = "from Employee e where e.name = :name"  
  13.         )  
  14.     }  
  15. )  
  16.   
  17. @Entity  
  18. @Table(name="em")  
  19. public class Employee {  
  20.       
  21.     public String toString(){return id+" "+name+" "+salary+" "+job;}  
  22.       
  23.     int id;  
  24.     String name;  
  25.     int salary;  
  26.     String job;  
  27.     @Id  
  28.     @GeneratedValue(strategy=GenerationType.AUTO)  
  29.        
  30.     //getters and setters  
  31. }  

hibernate.cfg.xml

It is a configuration file that stores the information's about the database such as driver class, URL, username, password and mapping class, etc.

  1. <?xml version='1.0' encoding='UTF-8'?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC  
  3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
  4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  
  5.   
  6. <hibernate-configuration>  
  7.   
  8.     <session-factory>  
  9.         <property name="hbm2ddl.auto">update</property>  
  10.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
  11.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>  
  12.         <property name="connection.username">system</property>  
  13.         <property name="connection.password">jtp</property>  
  14.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>  
  15.     <mapping class="com.tpoint.Employee"/>  
  16.     </session-factory>  
  17.   
  18. </hibernate-configuration>  

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.

  1. package com.tpoint;    
  2.     
  3. import java.util.*;  
  4. import javax.persistence.*;  
  5. import org.hibernate.*;  
  6. import org.hibernate.boot.Metadata;  
  7. import org.hibernate.boot.MetadataSources;  
  8. import org.hibernate.boot.registry.StandardServiceRegistry;  
  9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
  10.     
  11. public class Fetch {    
  12. public static void main(String[] args) {    
  13.     
  14.      StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();  
  15.         Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
  16.           
  17.         SessionFactory factory=meta.getSessionFactoryBuilder().build();  
  18.         Session session=factory.openSession();  
  19.                     
  20.     //Hibernate Named Query    
  21.            TypedQuery query = session.getNamedQuery("findEmployeeByName");    
  22.             query.setParameter("name","amit");   
  23.                     
  24.             List<Employee> employees=query.getResultList();   
  25.             
  26.     Iterator<Employee> itr=employees.iterator();    
  27.      while(itr.hasNext()){    
  28.     Employee e=itr.next();    
  29.     System.out.println(e);    
  30.      }    
  31.     session.close();     
  32.   }    
  33. }

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 a case, you need to create hbm file that defines the named query. Other resources are the same as given in the above example except for Persistent class Employee.java where you don't need to use any annotation and hibernate.cfg.xml file where you need to specify mapping resources of the hbm file.

The hbm file should be like this:

emp.hbm.xml

  1. <?xml version='1.0' encoding='UTF-8'?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC  
  3.           "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
  4.           "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
  5.   
  6. <hibernate-mapping>  
  7. <class name="com.tpoint.Employee" table="em">  
  8. <id name="id">  
  9. <generator class="native"></generator>  
  10. </id>  
  11. <property name="name"></property>  
  12. <property name="job"></property>  
  13. <property name="salary"></property>  
  14. </class>  
  15.   
  16. <query name="findEmployeeByName">  
  17. <![CDATA[from Employee e where e.name = :name]]>  
  18. </query>  
  19.    
  20. </hibernate-mapping>  

The persistent class should be like this:

Employee.java

  1. package com.tpoint;  
  2. public class Employee {  
  3.     int id;  
  4.     String name;  
  5.     int salary;  
  6.     String job;  
  7.     //getters and setters  
  8.  

Now include the mapping resource in the hbm file as:

hibernate.cfg.xml

  1. <mapping resource="emp.hbm.xml"/>