Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

org.hibernate.lazyinitialization exception

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: pojo.Person.address, no session or session was closed.

I am getting this exception and I'm using Spring 3.0 and Hibernate 3.6.

like image 842
Nandkumar Tekale Avatar asked Mar 28 '26 00:03

Nandkumar Tekale


1 Answers

It looks like you have an Entity called Person which has a lazily loaded mapped collection of Addresses? You have loaded the Person and the session it was loaded in has now been closed.

After the session was closed you then attempted to access that collection of address and Hibernate attempted to load them. However, that is not possible if the original session is no longer available.

In order to access the address property you have a few options:

  1. Use the OpenSessionInView pattern to ensure that the Hibernate session is held open for the duration of the request/response cycle (Since you've tagged Spring MVC I'll assume this is a web based operation). This essentially scopes your Hibernate session to the HTTP request.

  2. Ensure that all required properties are loaded before the session is closed (transaction committed). You can do this using

    Hibernate.initialize(person.address)

or by writing HQL that uses a left join fetch. This could be something like:

createQuery("from Person as person left join fetch person.address")

This will override any lazy loading configuration for this query only and ensure that any collections are initialized.

like image 80
Alex Barnes Avatar answered Mar 29 '26 13:03

Alex Barnes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!