This forum is now a read-only archive. All commenting, posting, registration services have been turned off. Those needing community support and/or wanting to ask questions should refer to the Tag/Forum map, and to http://spring.io/questions for a curated list of stackoverflow tags that Pivotal engineers, and the community, monitor.

AnnouncementAnnouncement Module

Collapse

No announcement yet.

Multiple HibernateTemplate Method Invocations In Single SessionPage Title Module

Multiple HibernateTemplate Method Invocations In Single Session

Jun 20th, 2006, 02:45 PM

What is the best way to invoke multiple HibernateTemplate template methods in a single session?

It seems like HibernateTemplate will open a new session if there's not a current one, do the method operation, then close the session. However, when there are multiple steps required, this isn't so useful.

For instance, to intialize an object's lazy-fetched collections, we need to re-attach the object, then we can invoke initialize() using the open session; i.e.

Comment

If they're done in the same thread, the session is re-used. Are you using different threads?

I remembered that HibernateTemplate instances are thread-safe and took care of opening and closing sessions. Since this is a web app, there will be a different thread-per-request; however, the problems I've been encountering are when I'm the only user, running Tomcat on my local machine, and doing a single request.

If I write the re-attach and initialize method the following way, I get an exception on the initialize() method call:

Comment

Thank you for your message. It gave me a hint how to deal with lazy collection post-loading after processing HQL query.

Of course, each your call to HibernateTemplate will open a new Hibernate session and close it, so, you attempt to attach an object to a session using lock() call has no effect, as the session is closed afterwards. What you need is to implement HibernateCallback and execute all operations (list() + Hibernate.initialize()) in one hibernate session via getHibernateTemplate().execute().

Comment

Furthermore, some operations just make sense within transactions, for example: contains, evict, lock, flush, clear.

By default HibernateTemplate will use the same existing transaction for all the operations. That means that while in a transaction you can call HibernateTemplate.initialize at any point and it will work. Or HibernateTemplate.lock + HibernateTemplate.initialize if the master record was loaded in a different transaction.

The way to implement an 'initialize' method that works outside of transactions in a HibernateDaoSupport's subclass is this: