to retrieve a lazy collection you do have to call either
Code:
Hibernate.initialize (root.getCollection())
or
Code:
root.getCollection ().size ()
at some point while the session is open and root is associated with it (or in its first level cache - in hibernate's terminology).
Given that fact you have few chioces here I will give them to you in the order I prefer (last being the most preferred, but most dificult to achieve) them:
1. Keep a session open all the time (attach it to your HTTP session) and use disconnect and reconnect for DB connection on each request or right before and after there is a save or update request. This might be problematic in regards to stale data. This approach is a
BIG NO if you have data that is accessed from two or more different places.
2. Open new session upon submission of the new request, reassociate the root object with the new session, and close the session upon request's completion. This will make sure that whenever your request is processing anything there is always a session available, to avoid lazy collections problem. You can use ThreadLocal variable to help you out with this or use request attributes along with a filter. Alternatively, make use of Spring and many of your headaches will disappear into the thin air (well given that you will take some time to read Spring docs :-))
3. Use aspects to non-intrusively open session and close it. You will have to dig deep to figure this one out yourself. It is not that I do not want to give you my solution, I just think I am not good enough at AOP to give out my solutions, not yet anyway :-)
My initial findings into this approach is that you will probably have to use AspectJ here to create classes with the capability of opening/closing a session whenever neccessary "burned in". The reason for it is that hibernate created objects can not be custom proxied. So I can not make use of Spring AOP or dynaop or any of the other dynamic AOPs, because those frameworks have to create your objects to introduce the aspects. So if hibernate creates your objects they are aspects free. Even though it is possible to make hibernate create the proxies (lazy collection, or proxy setting of a class set to true for lazy initialization of the object), it is impossible to make hibernate do it in a factory capable way, where user provides the factory to hibernate that is utilized to create the proxy. I might be wrong here, but this is where my reasearch left me so far and I was doing the reasearch for one week now.
I would definitely like to hear more discussion on the #3 somewhere, since it is a must if you are trying to create one of those rich domain models.
HTH