I am attempting to 'fix' and application that was built by a set of developers who were just learning Hibernate...and I know even less Hibernate. The application is filled with direct calls to DAOs rather than using services, and make extensive us of HibernateTemplate despite being hibernate 3. A co-worker and I are attempting to put OpenSessionInviewFilter in play to at least get lazy-loading, dynamic updating, and first level cache into play.
However, contrary to our expectations, I subclassed OSIVF and logged out when getSession is called and the hashCode of the object, and despite the presence of OSIVF, each service/DAO method called by the controller code is getting it's own session. Thing did improve a bit, in that once in a method marked @Transactional, it appears that within that method, sessions are being reused. But controller code transitions between pages, and has modularity, and I don't think it's reasonable to mark the controller code @Transactional (that should be done to model code).
How can I get these separate methods to behave as expected...ie using the same session for the duration of the request?
Load all the data you need when you are inside of a transaction in your service layer, that way it will be available when the transaction ends and the entity becomes detached. If you know you need the data than eagerly load it, and you wont have any lazy load exceptions.