Alain Cruz
Alain Cruz

Reputation: 5097

Spring @Transactional. How does it really work?

We are using Spring and Hibernate in our project. We are using Spring transactional annotations and we understand what it does, but we still have some doubts regarding rollbacks.

Let's say we have the following code.

@Transactional
@Service
public class PersonServiceImpl implements PersonService {

    @Autowired
    private PersonDao personDao;

    @Autowired
    private AnotherService anotherService;

    @Override
    public void doSomething() throws Exception {
        Person person = new Person();
        person.setName("John");
        personDao.insert(person);
        person.setName("Megan");

        //What happens if the following call fails and throws and exception.
        personDao.update(person);

        // What happens if this other service's call fails?
        anotherService.doSomethingElse();
    }

}

If either the update or the other service's call fails, what would happen to the insert? Would there be a rollback and the insert would never be executed? Or would the insert still persist in the DB? Do I need to declare the following command in each method for the rollback to be executed.

@Transactional(rollbackFor= Exception.class)

If that is the case, what happens if my service call throws the exception? Would it still works? Thanks for the help. I would really liked to understand the way rollbacks are executed inside a service call.

Upvotes: 1

Views: 141

Answers (1)

Stanislav Bashkyrtsev
Stanislav Bashkyrtsev

Reputation: 15316

By default if the exception is checked (extends Exception), the rollback won't happen - the transaction will be committed. Otherwise (if defaults were changed or we're talking about unchecked exceptions), the transaction is rolled back and INSERT/UPDATE statements don't persist anything. BTW, this is described in the JavaDocs to the rollbackFor attribute ;)

If the exception is eventually thrown from your Transactional method it doesn't matter where that exception originated.

If you're not sure about the behaviour, you can always debug Spring's HibernateTransactionManager and its superclasses.

Upvotes: 3

Related Questions