• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

How to visit lazy-loaded member outside Session scope?

Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I have one question about how to transfer object instance when using Hibernate lazy-loading.

In order to improve the performance, we usually use the lazy-loading on 'One-To-Many'. However, the lazy-loading can only be used under the Hibernate Session scope.

Assuming that the transaction scope was set on the methods of 'Service' tier, we can get the Entity object by calling the 'Service' method, but can't visit the lazy-loaded Collection member of this Entity object outside the 'Service' method, for example, in the 'View' tier. Because the Session has been closed outside the 'Service' method.

So how can we transfer the lazy-loaded Collection type member outside the Session scope? If we directly return the new Collection by copying the elements of the lazy-loaded Collection, I think it may break the Hibernate's original intention on Object Orientation.

Can anybody help to provide a best practice?


Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you can't keep the session open (following the "Open session in view" pattern; check this article out), your service is the one to take care of preparing the transfer object properly. That is - loading all the data you will need in the view layer.
You don't have to return any new, separate collection. You may return just the entity, however forcing Hibernate to fetch the lazy associations you want.
One way you can do it is by using a query hint (select p from parent p join fetch p.children).
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To force initialization of a proxy or persistent collection, there are 2 ways I know:
1. Use fetch-join strategy (can be in hbm.xml or java code)
2. User org.hibernate.Hibernate.initialize(object) method

I personally do not like "open session in view" pattern.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
    Bookmark Topic Watch Topic
  • New Topic