Reputation: 215
I'm new to hibernate and i have this problem.
If i do this:
Session sesion = HibernateUtil.getSessionFactory().openSession();
Transaction tx = sesion.beginTransaction();
A obj = (A) session.load(A.class,id);
System.out.println(obj);
tx.commit();
session.close();
return obj;
There is no problem and the gui shows the object's data.
But if i do this:
Session sesion = HibernateUtil.getSessionFactory().openSession();
Transaction tx = sesion.beginTransaction();
A obj = (A) session.load(A.class,id);
// i don't use System.out.println(obj);
tx.commit();
session.close();
return obj;
The gui doesn't show anything and i got the following exception.
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
I've been reading the api but it's a whole new world to me. Does anyone knows what's going on?
Upvotes: 1
Views: 441
Reputation: 860
Instead of using session.load(..)
, you need to use session.get(..)
A obj = (A) session.get(A.class,id);
The session.load(..)
lazy loads the object using a proxy, hence if the object is not accessed (in your example using System.out.println
) the object stays uninitialised. When an uninitialised object is accessed outside the hibernate session (called a detached object), a LazyInitializationException
is generated - as the proxy object has no way of retrieving the properties of the object from a hibernate session.
The session.get(..)
doesn't lazy load the object, so it is still accessible outside the session. There are few other nuances of get
vs load
, thus, I highly recommend you visit the following post about their difference:
Understanding Get vs Load: http://razshahriar.com/2009/01/hibernate-load-vs-get-differences/
Upvotes: 2
Reputation: 1539
load method use lazy loading to load its dependent(child) objects. If you do not read the object within session, it will throw LazyInitializationException.
Use Hibernate.initialize(object) to initialize all the child objects so that you can use it without session.
Upvotes: 0