• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to visit lazy-loaded member outside Session scope?

 
Wei Geng
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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?

Thanks!


 
Tomasz Szymanski
Greenhorn
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).
 
Justin Chi
Greenhorn
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic