Search code examples
hibernateservletshttpsession

Life of an instance retrieved from Hibernate Session in HttpSession


I ll explain my problem with an example. In my JSP login page , each correct login puts an instance of an Object called 'User' which keeps data of the user logging into the HttpSession(session.setAttribute("user",userObject)).How that object is created is, that user's username and password are checked and an instance('User') of User object is retrieved from HibernateSession.
In another page, when I retrieve above set userObject from HttpSession, the object can be retrieved without error. But when its methods are called, it gives an exception org.hibernate.LazyInitializationException: could not initialize proxy - no Session .Why I cannot that userObject from HttpSession even though I have put it earlier?

Why an empty object(instance variable have no values) exists in HttpSession even though the object had values earlier when it add to the session?


Solution

  • That can happen if the User entity has a collection property which is lazily fetched. The collection will then only be actually filled with the data from the DB when the caller actually needs to access it by e.g. size(), iterator(), etc. This needs to happen within the very same Hibernate session as when the User is been retrieved. In a properly designed webapplication the Hibernate session has namely a lifespan of exactly one HTTP request-response. So if accessing the collection property happens in a different Hibernate session (read: a different HTTP request), then you will get exaclty this exception.

    To fix this, you either need to fetch the collection property eagerly, or to use Hibernate#initialize() on the collection property while retrieving the User.

    See also: