Hibernate Session

The main function of a Hibernate session is to open a database connection, and offer read and update operations for instances. Each instance object associated with the session will keep alive until the session is closed or the object is deleted.

As the session is a light weight and a non thread safe object, session objects should not be kept for a long time. A session is opened by a SessionFactory, and is closed when all work is complete. In Hibernate, instances have three states:

  • transient – not associated with any session
  • persistent – associated with a single session
  • detached – previously persistent state, now not associated with any session. Detached objects can be passed across layers all the way up to the presentation layer (DTO still a better practice). The detached objects can be reattached to another session later.

The diagram shows how the states of the instance change.
hibernate instance states: transient, persistent and detached
A typical transaction will look like below:

If the Session throws an exception, the transaction must be rolled back and the session discarded. Make sure don’t leave the session not closed over long time. Otherwise, if there are lots of sessions created, but never closed , you will see the memory usage will grow up very fast, and you may see Out Of Memory error in the future.

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on RedditShare on StumbleUponEmail this to someoneShare on TumblrDigg this

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">