Clinton Bosch
Clinton Bosch

Reputation: 2589

Hibernate lazy loading in detached objects

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?

Upvotes: 20

Views: 16762

Answers (4)

Prateek Singh
Prateek Singh

Reputation: 1114

<prop key="hibernate.enable_lazy_load_no_trans">true</prop> 

you can add this line into your configuration file,it can fetch your lazy objects even it is detached,but it should be use post 4.1.7 version as there are some connection leakage issue with previous version.see here

Upvotes: 2

skytteren
skytteren

Reputation: 515

I know that you asked for Hibernate but EclipseLink has this feature so it might be worth checking out if you are using JPA and not tied to a given implementation. You might run into other problems migrating to EclipseLink though..

Upvotes: 1

pakore
pakore

Reputation: 11497

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.

Upvotes: 3

Bozho
Bozho

Reputation: 597124

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.

Upvotes: 15

Related Questions