Friday, 15 June 2018

Hibernate Query Language(HQL) Examples

             HQL is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. It is a superset of the JPQL, the Java Persistence Query Language; a JPQL query is a valid HQL  query, but not all HQL queries are valid JPQL queries.

             HQL is a language with its own syntax and grammar. It is written as strings and it will convert into conventional SQL queries; Hibernate also provides an API that allows you to directly issue SQL queries as well.

             Keywords like SELECT, FROM, and WHERE, etc., are not case sensitive, but properties like table and column names are case sensitive in HQL.

Advantages:--

  • Instead of returning plain data, HQL queries return the query result(s) in the form of object(s)/tuples of object(s) that are ready to be accessed, operated upon, and manipulated programmatically. This approach does away with the routine task of creating and populating objects from scratch with the "result set" retrieved from database queried.
  • HQL contains many advance features such as pagination, fetch join with dynamic profiling, and so forth, as compared to SQL.

Examples:

I have a given one example student entity, contains fields id, name and age as below,

Student.java,

package com.adnblog;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "student")
public class Student{
    
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @Column(name = "student_id")
      private Integer id;
     
      @Column(name = "student_name")
      private String name;
     
      @Column(name="student_age")
      private Integer age;
     
      public Integer getId() {
           return id;
      }
 
      public void setId(Integer id) {
           this.id = id;
      }
 
      public String getName() {
           return name;
      }
 
      public void setName(String name) {
           this.name = name;
      }
 
      public Integer getAge() {
           return age;
      }
 
      public void setAge(Integer age) {
            this.age = age;
      }   
}



  • HQL SELECT Query Example:--
The below query is to select the student where id is 121.


Query query = session.createQuery("from Student where id= :id");
query.setParameter("id", "121");
List list = query.list();

Equivalent sql query is,


Select * from student where student_id = 121;

The above query is same as SQL Query but in this we can use entity name as table name and field name as column name.

  • HQL UPDATE Query Example:-
The below query is to update the student name where id is 121.

Query query = session.createQuery("update Student set name= :name" +
        " where id= :id");
query.setParameter("name", "Mahesh");
query.setParameter("id", 121);
int result = query.executeUpdate();

Equivalent sql query is,

UPDATE student SET student_name = 'Mahesh'
          WHERE student_id= 121;


  • HQL DELETE Query Example:-

The below HQL query is to delete the Student from student table where id is 121.

Query query = session.createQuery("delete Student where id= :id");
query.setParameter("id", 121);
int result = query.executeUpdate();

Equivalent SQL query is,

DELETE FROM student where student_id = 121;


  • HQL INSERT Query Example:

          HQL supports only the INSERT INTO .....  SELECT……… ; there is no chance to write
 INSERT INTO ..... VALUES, it means while writing the insert query, we need to select
values from other table, we can’t insert our own values manually.

Query query = session.createQuery("insert into Student(id, name)" +
       "select student_id, student_name from other_student_table");
int result = query.executeUpdate();

Equivalent SQL Query is,


INSERT INTO student(studnet_id, student_name) 
SELECT student_id, student_name FROM other_student_table;

Thank you for visiting blog.....



Related Posts:--
1) What is a Hibernate Caching ? Explain first level and second level cache in Hibernate
2) What are different states of an entity bean in Hibernate?
3) Hibernate One to One Mapping Example - Annotation based
4) Hibernate - JPA Annotations with explanation
5) Advantages of Hibernate over JDBC
6) What are the Core Interfaces of Hibernate framework ?

Monday, 11 June 2018

What is a Hibernate Caching ? Explain first level and second level cache in Hibernate

       In previous post, learned the different states of an entity bean in Hibernate.  In this we will learn the caching mechanism and first and second level cache in Hibernate.
        

What is Caching in Hibernate ? 

       Caching is a mechanism for storing the loaded objects into a cache memory.  The advantage of caching mechanism is, whenever again we want to load the same object from the database then instead of hitting the database once again, it loads from the local cache memory only, so that the no. of round trips between an application and a database server got decreased.  It increases the performance of the application.

There are mainly two types of caching:-
  •  First Level Cache 
  •  Second Level Cache.     


First Level Cache:-

        First level cache is associated with “session” object. The scope of cache objects is of  session. Once session is closed, cached objects are gone forever.
       First level cache is enabled by default and you can not disable it. When we query an entity first time, it is retrieved from database and stored in first level cache associated with hibernate session. If we query same object again with same session object, it will be loaded from cache and no sql query will be executed. The loaded entity can be removed from session using evict() method. The next loading of this entity will again make a database call if it has been removed using evict() method. The whole session cache can be removed using clear() method. It will remove all the entities stored in cache.

Example:--
    
       In this example, I am retrieving Department object from database using hibernate session.
I will retrieve it multiple times, and will observe the sql logs to see the differences.

//Open the hibernate session
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
 
//fetch the department entity from database first time
Department department = (Department) session.load(Department.class, new Integer(1));
System.out.println(department.getName());
 
//fetch the department entity again(second time)
department = (Department) session.load(Department.class, new Integer(1));
System.out.println(department.getName());
 
session.getTransaction().commit();
HibernateUtil.shutdown();
 


Output:

Hibernate: select department0_.ID as ID0_0_, department0_.NAME as NAME0_0_ from DEPARTMENT department0_ where department0_.ID=?
IT
IT

evict() and clear() method in Hibernate:-

evict():  Removes the object from the session. This method is used to dissociate/disconnect the specified object from the session.

clear () :  When this method get called inside transaction boundry then all objects  which are currently associate with particular session will be  disconnected / clean or no longer associate with that Session instance.


Second Level Cache:--

            Second level cache is associated with Session Factory.   It is created in session factory scope and is available to be used in all sessions which are created using that particular session factory. It also means that once session factory is closed, all cache associated with it die and cache manager also closed down.
           Whenever hibernate session try to load an entity, the very first place it look for cached copy of entity in first level cache (associated with particular hibernate session). If cached copy of entity is present in first level cache, it is returned as result of load method. If there is no cached entity in first level cache, then second level cache is looked up for cached entity. If second level cache has cached entity, it is returned as result of load method. But, before returning the entity, it is stored in first level cache also so that next invocation to load method for entity will return the entity from first level cache itself, and there will not be need to go to second level cache again. If entity is not found in first level cache and second level cache also, then database query is executed and entity is stored in both cache levels, before returning as response of load() method.

           Second Level Cache is not enabled by default, there are different vendors provided the implementation of Second Level Cache,

  • EH Cache
  • OS Cache
  • Swarm Cache
  • JBoss Cache

           Each implementation provides different cache usage functionality. There are four ways to use second level cache.

read-only:  caching will work for read only operation.

nonstrict-read-write: caching will work for read and write but one at a time.

read-write: caching will work for read and write, can be used simultaneously.

transactional: caching will work for transaction.


Example :--
     
     In the below example, we are using EH Cache provider implementation of Second Level Cache.

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-configuration PUBLIC  
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
    
<hibernate-configuration>  
  
    <session-factory>  
        <property name="show_sql">true</property>  
        <property name="hbm2ddl.auto">update</property>  
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>  
        <property name="connection.url">jdbc:mysql://localhost/sample</property>  
        <property name="connection.username">root</property>  
        <property name="connection.password">root</property>  
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>  
        
        <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>  
        <property name="hibernate.cache.use_second_level_cache">true</property>  
       
    </session-factory>  
  
</hibernate-configuration>

SampleTest.java,

package com.adnblog;  
  
import org.hibernate.Session;  
import org.hibernate.SessionFactory;  
import org.hibernate.cfg.Configuration;  
  
public class SampleTest {  
     public static void main(String[] args) {  
          Configuration cfg=new Configuration().configure("hibernate.cfg.xml");  
          SessionFactory factory=cfg.buildSessionFactory();  
      
          Session session1=factory.openSession();  
          Student std1=(Student)session1.load(Student.class,121);  
          System.out.println(std1.getId()+" "+std1.getName());  
          session1.close();  
      
          Session session2=factory.openSession();  
          Student std2=(Student)session2.load(Student.class,121);  
          System.out.println(std2.getId()+" "+std2.getName());  
          session2.close();  
      
     }  
}  
  
Output :--  select student0_.id as id0_0, student0_.name as name0_0 from STUDENT student0_ where student0_.id = ?
                   18 Mahesh M
                   18 Mahesh M

Thank you for visiting blog.


Related Post:-
1) What are different states of an entity bean in Hibernate?
2) Hibernate One to One Mapping Example - Annotation based
3) Hibernate - JPA Annotations with explanation
4) Advantages of Hibernate over JDBC
5) What are the Core Interfaces of Hibernate framework ?
6) Spring MVC with Hibernate CRUD Example