Monday, 13 August 2018

Cause and solution of LazyInitializationException in Hibernate

        In previous post, we discussed the difference between the update and merge methods in Hibernate.  In the current post we will discuss Cause and Solution of  LazyInitializationException in Hibernate.

       This exception occurs when the Hibernate Session is closed and object becomes detached.  And if you try to access properties or associated object of Detached object then it results in org.hibernate.LazyInitializationException: could not initialize proxy - no session Exception.

       In other words, we can say Hibernate does not support lazy initialization for detached objects. Access to a lazy association outside of the context of an open Hibernate session will result in an LazyInitializationException.

Here is the example:--,

@Table (name="employee")
public class Employee {
     private int id;
     private String name;
     @OneToMany(cascade=CascadeType.ALL, FetchType.LAZY) 
     private Set<Address> address;
        // setters and getters

         In the above example, Employee and Address entity have the One to Many relationship. The default fetch type of One to Many relationship is LAZY.,

@Table (name="address")
public class Address {
     private int id;
     private String address;
        // setters and getters

The Hibernate class to get the details from entity as follows,,

package com.adnblog;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.adnblog.Employee;

public class HibernateMain {

      public static void main(String[] args) {

            SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
            Session session = sessionFactory.openSession();
            Employee emp = session.get(Employee.class, 1); 
            emp.getId();                     // will throw LazyInitializationException                     

The above code throw the error:--
Exception in thread "main" org.hibernate.LazyInitializationException: could not initialize proxy - no Session


Use FetchType.EAGER of field address_id in  Employee entity, So that whenever you call the session.get() method, will load all the details from database. Even if you close the session you will get employee details.

Thank you for visiting blog.

Related Post:--
1) Hibernate - JPA Annotations with explanation
2) What are different states of an entity bean in Hibernate?
3) Difference between Update and Merge methods in Hibernate with example
4) What is a Hibernate Caching ? Explain first level and second level cache in Hibernate
5) What is the difference between get() and load() methods in Hibernate?
6) Hibernate JPA Cascade Types
7) Difference between save() and persist() method in Hibernate
8) What is lazy loading in Hibernate? Explain with example

No comments:

Post a comment