Thursday, March 11, 2010

Hibernate Session and Transaction Management

It seems, there are several approaches to manage Hibernate sessions and transactions:
  • explicitly by the application
  • explicitly by the application with ThreadLocal pattern (example)
  • via Hibernate transaction demarcation with JTA
  • via Hibernate transaction demarcation with plain JDBC
  • using Spring Framework
  • using EJB / CMT (container-managed transactions)
For a good explanation of all options, other than ThreadLocal, see Hibernate document. Note that EJB, as well as JTA, are available even outside the J2EE container as a module. Also, supposedly, the Spring Framework can be easily used just for the functionality you decide to use from it and it doesn't require the application to use all parts of this framework.

Basic Approach: Managed by Application
Here's a code sample from hibernate document:
Session session = factory.openSession();
Transaction tx = null;
try {
    tx = session.beginTransaction();

    // Do some work
    session.load(...);
    session.persist(...);

    tx.commit(); // Flush happens automatically
}
catch (RuntimeException e) {
    tx.rollback();
    throw e; // or display error message
}
finally {
    session.close();
}
You choose the approach.

No comments: