Spring Programmatic transaction within transaction

nestedspringtransactions

I have written below code doing below activities
I created one transaction using Spring classes.
Inserted one row.
Created other transaction.
Inserted another row.
committed outer transaction.
Rolledback inner transaction.

TransactionStatus trxstsOuter= dsTrxMngr.getTransaction(null);
    jdbcTemplate.update("insert into kau_emp values(6,'xyz' )");
    TransactionStatus trxstsInner= dsTrxMngr.getTransaction(null);
        jdbcTemplate.update("insert into kau_emp values(7,'pqr' )");

dsTrxMngr.commit(trxstsOuter);
System.out.println("trxstsOuter.isCompleted()" + trxstsOuter.isCompleted());
System.out.println("trxstsInner.isCompleted()" + trxstsInner.isCompleted());
dsTrxMngr.rollback(trxstsInner);
    System.out.println("trxstsInner.isCompleted()" + trxstsInner.isCompleted());

I observed that both the rows are committed to DB !!
The output is

trxstsOuter.isCompleted()true
trxstsInner.isCompleted()false
trxstsInner.isCompleted()true

Is it correct behavior ?
Should not inner transaction be first committed/rollbacked before allowing outer transaction to commit ?
If outer transaction was committed, should rollback of inner thrown an error ?

Best Answer

In your example transaction Propagation.REQUIRED is used as the default value, and all the logic transactions are mapped to the single physical transaction

When the propagation setting is PROPAGATION_REQUIRED, a logical transaction scope is created for each method upon which the setting is applied. Each such logical transaction scope can determine rollback-only status individually, with an outer transaction scope being logically independent from the inner transaction scope. Of course, in case of standard PROPAGATION_REQUIRED behavior, all these scopes will be mapped to the same physical transaction. So a rollback-only marker set in the inner transaction scope does affect the outer transaction's chance to actually commit (as you would expect it to).

So in your example two logical transactions are mapped to one physical transaction.

See the documentation

Related Topic