Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 813
Clinton Bosch Avatar asked Oct 05 '10 10:10

Clinton Bosch


People also ask

How lazy loading works internally in Hibernate?

Hibernate now can "lazy-load" the children, which means that it does not actually load all the children when loading the parent. Instead, it loads them when requested to do so. You can either request this explicitly or, and this is far more common, hibernate will load them automatically when you try to access a child.

How do you load a lazy object in Hibernate?

To enable lazy loading explicitly you must use “fetch = FetchType. LAZY” on an association that you want to lazy load when you are using hibernate annotations. @OneToMany( mappedBy = "category", fetch = FetchType.

Is Hibernate lazy load by default?

By default, Hibernate uses lazy select fetching for collections and lazy proxy fetching for single-valued associations. These defaults make sense for most associations in the majority of applications. If you set hibernate.


1 Answers

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.

like image 143
Bozho Avatar answered Nov 04 '22 12:11

Bozho