Search code examples
springspring-data-jpaspring-aopspring-transactions

@Transactional method calling a method in the same class


I have a class UserService which has a method saveUser() and saveAmount() as shown below.

class UserService {
    
    @Transactional
    public void saveUsers() {
        saveUser1 to db;
        saveUser2 to db;
        saveAmount();
        saveUser3 to db;
    }
    
    public void saveAmount() {
        saveAmount1 to db;
        saveAmount2 to db // throws exception
        saveAmount3 to db;
    }
}

As per Spring AOP, when saveAmount() is called, the proxy won't be triggered and we have the same transaction of saveUsers method continuing with saveAmount, so any exception in saveAmount (say in line 2 of the method) if occured will rollback saveUser1 to db and saveUser2 to db.

Question : Will saveAmount1 to db be rolled back as well ?

I tried replicating this on my local machine and I am expecting that saveAmount1 to db won't rollback as it was called from them same object and AOP did not kick in.


Solution

  • AOP does not kick it if you are self invoking a @Transactional method only means the @Transactional on the method that is being self-invoked will not have any effect.

    But now saveAmount() does not have any @Transactional annotated on it , so it is nothing to do with whether the AOP will kick in or not.

    In this case , both saveUsers() and saveAmount() execute in the same transaction. All codes in the same transaction has all or nothing behaviour meaning the changes to DB are either all success or all fail. All fail also imply that any codes that throw exception will rollback all DB changes that are executed successfully. So if saveAmount2 throws exception , every DB changes will rollback including saveAmount1.