Why is HIbernateTransactionManager required in Spring?

ramu p picture ramu p · Feb 7, 2014 · Viewed 9.7k times · Source

When we can do transactions in hibernate through session, what is the need of HibernateTransactionManager again in Spring-hibernate integration?

What is the role of it?

Why can't we do transactions directly without this?

Answer

JB Nizet picture JB Nizet · Feb 7, 2014

What Spring allows to do, thanks to AOP, is to use declarative transactions, like you could do with EJBs.

Instead of doing

public void doSomething() {
    Session sess = factory.openSession();
    Transaction tx = null;
    try {
        tx = sess.beginTransaction();

        // do some work
        ...

        tx.commit();
    }
    catch (RuntimeException e) {
        if (tx != null) tx.rollback();
        throw e; // or display error message
    }
    finally {
        sess.close();
    }
}

You simply do

@Transactional
public void doSomething() {
    // do some work
}

Which is much more readable, more maintainable, less cumbersome, and safer since Spring handles the transactional logic for you. That's why a transaction manager is needed: to tell Spring how it should handle the transactions for you. Because it can also use the same declarative model but use JPA transactions, or JTA transactions.

This is well described in the Spring documentation.