I have created a class in which I have set some of it's fields (other entities) to be LAZY loaded. Now I need to use this object after it has been detached from the session, so I obviously need to make sure all the fields that I need are populated before detaching it. I tried just calling the getters to these lazy fields but that didn't seem to work. Anyone have an idea how to force these fields to be loaded?
+3
A:
Hibernate.initialize(yourObject)
will force-initialize the object/collection that is passed to it. You need an active session for this.
If the entity is detached, you'd have to re-attach the object (using merge(..)
) to an active session and then initialize it.
Bozho
2010-10-05 10:19:56
+1 Bozho.........
org.life.java
2010-10-05 10:22:33
`merge` is just for some very special cases. As a rule of a thumb I'd recomment `update`
pakore
2010-10-05 10:24:25
@pakore - well, the difference I think is that `merge(..)` can insert a new record as well. But I'm more used to the JPA semantics, so it might be a bit different here.
Bozho
2010-10-05 10:31:04
Hibernate.initialize is not transitive I believe. So if your object has a lazy collection or lazy field, you need to do Hibernate.initialize(object.getLazyField()) or .initialize(object.getLazyCollection())
Barthelemy
2010-10-05 10:32:38
@Berthelemy - true
Bozho
2010-10-05 10:45:04
+1
A:
You can reattach it to the session. This is the normal way.
session.update(yourObject); //This reattachs the object to the current session.
yourObject.someGetter(); //This will work now.
pakore
2010-10-05 10:23:40