HibernateDaoSupport
.The goal is to deal with transactions like this:
public void doSomething() {
Transaction txn = null;
try {
txn = getTransaction();
txn.begin();
// do something here
if (txn.isActive()) txn.commit();
} catch (Exception e) {
try {
txn.rollback();
} catch (Exception ignore) {}
throw e;
} finally {
freeTransaction();
}
}
The follwoing method returns a
org.hibernate.Transaction
object that contains the expected methods for transaction handling, like begin()
, commit()
, and rollback
:protected final Transaction getTransaction() {
Session session = getSession();
SessionFactory factory = getSessionFactory();
if (TransactionSynchronizationManager.getResource(factory) == null) {
TransactionSynchronizationManager.bindResource(factory,
new SessionHolder(session));
}
return session.getTransaction();
}
When the transaction is no longer needed, its resources should be freed:
protected final void freeTransaction() {
try {
TransactionSynchronizationManager.unbindResource(getSessionFactory());
} catch (Exception ignore) {}
try {
getSession().close();
} catch (Exception ignore) {}
}