Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is HIbernateTransactionManager required in Spring?

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?

like image 254
ramu p Avatar asked Feb 07 '14 10:02

ramu p


1 Answers

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.

like image 54
JB Nizet Avatar answered Nov 05 '22 11:11

JB Nizet