Search code examples
javaspringspring-bootspring-transactionsmulti-database

Transaction inside transaction support? (multi database) in Spring boot


I have DB1, DB2. I config two DataSource and two PlatformTransactionManager for two database (within the same physical machine). I have this code:

@Transaction("DB1")
public void A() {
    B();
}
@Transaction("DB2")
public void B() {
}

When B() has an SqlException, data in DB1 did not rollback. How to implement rollback DB1? Thank very much.


Solution

  • @Transaction annotation has an attribute rollbackFor (@Transaction(value = "DB1", rollbackFor = SqlException.class) for example) that may cover your needs.

    However, there is only one transaction will be actually used in your code, because B is invoked not via Spring proxy but via inner call (this.B()). To execute method inside a separate transaction method must be invoked via Spring proxy - someService.B(), not this.B().