jimmayhem
jimmayhem

Reputation: 405

Why do we need to use @Transactional if Hibernate already uses getTransaction() for each session?

I am new to Hibernate. As far as I understood all modifying actions with Hibernate are done inside entityManager.getTransaction().begin() and entityManager.getTransaction().commit(), hence Hibernate under the hood always does everything within transaction boundaries (except for read-only operations). If so, why do we need to explicitly use @Transactional annotation?

UPDATE

So basically I can write something like

void foo() {
    try {
        em.getTransaction().begin();
        ...
        em.persist(a1); // 1 operation
        ...
        em.persist(a2); // 2 operation
        ...
        em.commit();
    catch (Exception e) {
        em.rollback();
        throw new RuntimeException(e);
    }
}

which is equivalent to

@Transactional
void foo() {
    em.persist(a1);
    ...
    em.persist(a2);
}

or if I want to split all my actions into more than one method, I create one wrapper method, annotate it with @Transactional and then call other methods within this wrapper method

@Transactional
void call() {
    foo();
    bar();
}

void foo() {
    em.persist(a1);
}

void bar() {
    em.persist(a2);
}     

And both foo() and bar() will be executed in terms of one transaction, is that correct?

Upvotes: 1

Views: 1029

Answers (1)

SpaceTrucker
SpaceTrucker

Reputation: 13546

If you only ever make a single insert/update/delete per transaction, yes than using @Transactional is unnecessary. But if you want to make multiple insert/update/delete than @Transactional can be used to group all those to a single transaction.

Upvotes: 1

Related Questions