Monday, June 08, 2009

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 newSessionand 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 Sessionwill be closed. In this approach you can user the Filter in servlets APIs . this approach is called session-per-conversation and used while implementinglong conversations.

The third technique and the most recommended technique is using java transaction APIs. Hibernate can automatically bind the "current"Sessionto the current JTA transaction. This enables an easy implementation of the session-per-requeststrategy with thegetCurrentSession()method on yourSessionFactory:

try {

UserTransaction tx = (UserTransaction)new InitialContext()

.lookup("java:comp/UserTransaction");

tx.begin();

// Do some work

factory.getCurrentSession().load(...);

factory.getCurrentSession().persist(...);

tx.commit();

}

catch (RuntimeException e) {

tx.rollback();

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'sTransactionand the built-insession-per-request functionality:

3 comments:

Good article, however, there is another alternative way only in case you use spring. Spring provides some extra support for using hibernate by marking the methods that needs transactional support in a certain class, for example; if you have a service class that calls DAOs, then, the logic in these methods are transactional, either done completely or rolled back, spring uses a simple proxy class to wrap the service class methods and automatically commit or roll back the database actions done according to the success or failure of a method. for more details see TransactionalProxyFactroyBean class of spring.

About us

We are a group of bloggers from Faculty of Computers & Information, Helwan University. We have a passion for technology, enjoy programming and we enjoy blogging. This blog is the result of combining those skills and the desire to share our knowledge with others.