When the transaction will be committed?

Viewed 88

I need some clarification regarding Spring transation. In ClassA I am creating a declaritive transaction. From ClassA I am calling method1() of ClassB. ClassB is having @Transactional(propagation = Propagation.REQUIRED) annotation in classs level. In method1() I am doing a save operation.

My question is, when that data will be committed ? Will it be committed while control will come out from method1()? or in ClassA where we are committing the transaction manually ?.

Code:

ClassA

class ClassA {

    void myMethod() {
        TransactionStatus status = null;
        DefaultTransactionDefinition def =
                new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        def.setTimeout(contentFileProcessingConfigBean.getFileCopyTransactionTimeout());
        status = transactionManager.getTransaction(def);

        b.method1();

        if (status != null) {
            transactionManager.commit(status);
        }
    }

}

ClassB

@Transactional(propagation = Propagation.REQUIRED)
class ClassB {

void method1() {

//doing save operation

}
}
1 Answers

Probably after B.method1() finishes the aspect which is wrapping the call to @Transactional (visible in the stack trace) will commit the transaction. However this will depend on:

  • Are A and B are both Spring beans?
  • Is the same transactionManager bean used by transactions in A and B?
  • Maybe if A is written using TransactionTemplate instead of plain TransactionManager object.

Mixing the manual and declarative transaction management is not recommended as you have to guess. I guess it will come to transactionManager which you are not showing.

Related