Hibernating session and garbage collector

Object with hibernate session data member when garbage collected is closed by jdbc session connection? In other words, is it a bad idea to leave the session closed to the garbage collector?

+2


source to share


3 answers


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



+2


source


totally agree with @Robert. It cannot be underlined enough, hibernate session objects must be handled with the same care as a JDBC connection, you must know when and where it opens, 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 lifecycle of resources like jdbc connections and hibernation sessions.

0


source


If your entities are garbage collected, there is no reason for a GC session either. The session will be GCed then or later.

For example, if I store the session reference in a static list, I can run the application for a few hours, the objects will receive the collection, but not the sessions ...

The session must be closed explicitly.


If you don't like explicit code closure, I totally agree with you and many other people. :-)

A common solution is closure in the framework code, that is, code that is written once and applied to all your transactions. This can happen in a superclass, for example, if all your transactions are implemented using a command template.

However, the most common implementation model is to use AOP for such a global problem. Our projects use Spring, which provides built-in support for closing all hibernation sessions (and associated transaction) with an additional function for commit / rollback :

  • if an exception is thrown, rollback is called for the transaction before closing
  • Otherwise commit is called.
0


source







All Articles