FCI-Helwan blog

Just another FCI-H weblog

Handling Hibernate Session

Handling hibernate session is so important, and the way of handling the session reflects with the performance of the application.

You can handle the hibernate session per service. It means with each request for each service you will open new session, at the end of the service, you will close the session. In this approach you have to be sure that you don`t need the session again (lazy fetching for example ).

p.s) if lazy fetching is false it will affect the performance.

Another approach of handling session is session per view. When an HTTP request has to be handled, a new Session and database transaction will begin. Right before the response is send to the client, and after all the work has been done, the transaction will be committed, and the Session will be closed. In this approach you can user the Filter in servlets APIs . this approach is called session-per-conversation and used while implementing long conversations.

The third technique and the most recommended technique is using java transaction APIs. Hibernate can automatically bind the “current” Session to the current JTA transaction. This enables an easy implementation of the session-per-request strategy with the getCurrentSession() method on your SessionFactory:

try {
    UserTransaction tx = (UserTransaction)new InitialContext()
    // Do some work
catch (RuntimeException e) {
    throw e; // or display error message

Finally If you don’t have JTA and don’t want to deploy it along with your application, you will usually have to fall back to JDBC transaction. Instead of calling the JDBC API you better use Hibernate’s Transaction and the built-in session-per-request functionality:


June 8, 2009 Posted by | Hibernate, JAVA | 1 Comment