If you have a call in a Dao method like (pseudo code):
return ..getHibernateTemplate( get by id );
Now say that entity has a lazy-loaded collection. Once you return from your Dao using the hibernateTemplate helper method, how come the session stays in scope and allows you to lazy-load a collection?
Is the session initialized and committed at a global level on a per request basis?
Update
Please explain where exactly the call to ‘getcurrentsession’ is made, and when is it actually closed/committed?
From what I understand, the spring framework has to handle the session lifecycle, where does it do this? at what point the in the requests lifecycle?
It is handling the Unit of work also, where/how?
Because the
Sessionhasn’t been closed yet and your entity is thus still Persistent (as opposed to the Detached object state). As long as your entity has not been detached, you can lazy load collections and proxies. See chapter 10.1. Hibernate object states for more details on these states (it’s very important to understand them and the terminology used).With web applications, it’s typically per request. As mentioned in the javadoc of
HibernateTemplate:And if you look at the javadoc of
OpenSessionInViewFilterorOpenSessionInViewInterceptor, you’ll read that they are slightly different but both binds a Hibernate Session to the thread for the entire processing of the request and provide an implementation of the “Open Session in View” pattern.You could look at the sources and use a debugger for this you know 🙂 Look at
HibernateTemplate, more precisely thedoExecute()method, this is where the session is obtained. For the close/commit, look at the previously mentionedOpenSessionInViewFilter/Interceptor, both have methods for this purpose.I think I covered that part: the session is created at the start of a request and closed at the end.
I’m not sure to get this one. To me, Hibernate’s Session is an implementation of the unit of work pattern. So this question is actually the same as the previous one.
PS: I provided some links that show that everything is actually clearly documented. Spring and Hibernate have extremely nice documentation and javadoc. Take advantage of that, look at them by yourself, look at the code by yourself, use your debugger, you’ll learn a lot more.