How to visit lazy-loaded member outside Session scope?
Joined: Dec 10, 2004
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?
Joined: Jan 11, 2010
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).
Joined: Sep 09, 2009
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.