Search code examples
javaspringtransactionsrollbacktransactional

Should I put @Transactional annotation for submethods also in spring?


I have a main DB handler method, which calls other methods, which are also working with BD things.

I put @Transactional annotation for the main method, because I want to roll back everything, if something goes wrong.

My question is: should I put this annotation also for the submethods, or it will know that the submethods were called from a method which is transactional.

For example, in the deleting method an exception occurs, how can I make sure that the writing part will be also rollbacked:

@Transactional
public void maintDbTings() {
    writing();
    deleting();
}

@Transactional //do I need this?
public void writing() {
    //no exceptions
}

@Transactional //do I need this?
public void deleting() {
    //exception occurs
}

Solution

  • Spring begins a transaction when it encounters a method annotated with @Transactional. The transaction’s scope covers the execution of that method, the execution of any methods that method invokes, and so on, until the method returns. Any managed resources that are covered by the configured PlatformTransactionManager and that you use during the transaction scope participate in the transaction. For example, if you use the org.springframework.jdbc.datasource.DataSourceTransactionManager, a Connection retrieved from the linked DataSource participates in the transaction automatically. The transaction terminates one of two ways: Either the method completes execution directly and the transaction manager commits the transaction, or the method throws an exception and the transaction manager rolls the transaction back.

    I hope it is clear now.