views:

259

answers:

3

An object with hibernate session data member when garbage collected, is session's jdbc connection closed? In other words is leaving closing session to garbage collector bad idea?

+2  A: 

You should always explicitly close resources, and not rely on GC/finalisation.

Robert Munteanu
A: 

completely agree with @Robert. It cannot be stressed enough, hibernate session objects should be treated with the same care as a JDBC connection, you should be aware of when and where it is opened and when and where it is closed in all cases.

This is of course one of the reasons people find spring very useful, it provides a very complete framework for managing the life cycle of resources like jdbc connections and hibernate sessions.

Gareth Davis
A: 

If your entities are garbage-collected, there is no reason to GC the session too. The session will be GCed then or later.

For example, if I store a reference to a session in a static list, I can run my application for hours, entities will get collected but not the sessions...

Session should be closed explicitely.


If you dislike the explicit closing in your code, I totally agree with you, and many other people also. :-)

A common solution is to make the closing happen in framework code, that is code that is written once, and applies to all your transactions. It could happen in a superclass, for example if all your transactions are implemented via the command pattern.

However, the most common implementation pattern is to use AOP for such a global concern. Our projects use Spring, which provide out-of-the-box support for closing all hibernate sessions (and the associated transaction), with an additional feature for commit/rollback:

  • if an exception is thrown, rollback is called on the transaction before closing it
  • otherwise, commit is called.
KLE