• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to lazily load references when the object is detached from session ?  RSS feed

Kumar Raja
Ranch Hand
Posts: 548
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have read that in order to lazily load objects and its references, the object and its references should always be attached to a session. This makes sense as, the proxies are associated with the session and out of session proxies does not have any value and can not be used. However, in most of the cases, especially in a multitier environment, a client's request may pass through many layers and at some where below the stack, the objects are retrieved under a session and returned back to calling object. In the calling object, there may/may not be having any references to session (may be that is completely unaware of a thing called Hibernate). In such cases, how can the objects and its references be still loaded lazily. I may better explain my question using an example.

Assume, I have two entities Person and Event.
Every Person can attain one or more events and I'm having a one-many unidirectional association between Person and Event.





After defining these files, I'm using a client application to persist Events and Persons and establishing associations between these two. I'm successful till here.

Now, I'm attempting to retrieve objects and my method is as follows

As you can see from this method this is returning only the proxies as I'm using load method instead of get. But when I try to invoke the method

on the reference I get for these objects, I get exception [b]1203 [main] ERROR org.hibernate.LazyInitializationException - could not initialize proxy - no Session. [b]. I can understand the reason for this exception, as at this point, object being referred by "e" is not associated with any session.

I can quickly overcome this issue, if I use "get" instead of "load", though I'm more interested in using load.

But what if, Event has references to some other entities, say "Address". How can I call
e.getAddress() like method, when I'm completely out of session control, except that I mention the reference retrieval as eager loading.

Is there any work around, where I can access objects and their references lazily, but yet outside a hibernate session.

David Newton
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, you need to be attached to a Hibernate session--this seems self-evident to me.

Options include using an OSiV-style filter or loading more data earlier in the process.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!