Using @Transactional on service method, which updates multiple repositories

Viewed 588

Spring boot, postgres, spring jpa.

Have a service, which is trying to store changes across multiple repositories:

class Service {

    @Transactional
    public void doStuff() {
        repo1.delete(...);
        repo2.saveAll(...);
        repo1.save(...);
    }
}

This operation requires to be rolled back if anything fails.

Here I struck into two things:

  1. If I add a throw RuntimeException somewhere in the middle of that method, all things before it don't get rolled back.
  2. In regular flow I get

Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction

My configuration is:

@Configuration
@EnableTransactionManager
@EntityScan
@EnableJpaRepositories
public class DataConfig {}

Also trying to use the TransactionTemplate bean with it's execute method. Manage to overcome the first issue, but still fail with the second one.

1 Answers

You can try by adding @Transactional(rollbackFor = Exception.class) this will rollback even if you have an exception in your code

class Service {

    @Transactional(rollbackFor = Exception.class)
    public void doStuff() {
        repo1.delete(...);
        repo2.saveAll(...);
        repo1.save(...);
    }
}
Related