Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




HQL - Named Queries

Say at times we do not want to keep the queries in our main code.

Query query = session.createQuery("from Employee employee WHERE employee.name= 'Joe'");

and replace "from Employee employee WHERE employee.name= 'Joe'" with a variable.

Luckily it can be achieved using 'Named Queries'.

So, we assume that the 'EMPLOYEE' table is already loaded.



EMPLOYEE

ID NAME
1 Joe
2 Peter
3 Chang

Where to write the Named Query?

The actual query can be written in the mapping file.



Employee.hbm.xml

<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
   <class name = "Employee" table = "EMPLOYEE">
     <id name = "id" type = "string">
       <column name = "ID">
     </id>
     <property name = "name" type = "string">
       <column name = "NAME">
     </property>

     <query name="empName">
       <![CDATA[from Employee employee WHERE employee.name= 'Joe']]>
     </query>

   </class>
</hibernate-mapping>

So, we have written the query in the mapping file inside '<query>' tag

<query name="empName">

in a particular format

<![CDATA[from Employee employee WHERE employee.name= 'Joe']]>

Now, let us write the main() class :


import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateSave {
   public static void main(String[] args) {

    static SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();

    Query query = session.getNamedQuery("empName");

    session.getTransaction().commit();

    session.close();
    sessionFactory.close();
   }
}

So instead of writing

session.createQuery(...);

We have used

Query query = session.getNamedQuery("empName");

Which takes the query from the mapping file by matching 'empName'

<query name="empName">
  <![CDATA[from Employee employee WHERE employee.name= 'Joe']]>
</query>