Spring @Transactional

Content:

Original link: We Killed @Transactional. Our Database Stopped Lying to Us. / Medium.

Spring @Transactional works exactly as documented.

But it does not work like the human brain would like to think it does.

The article does explain it, but I think it can use a more detailed explanation.

Look at these code snippets:

...
@Component("backend")
public class BackendService {
    ...
    @Transactional
    public void m1() {
        System.out.printf("m1 called - in tx : %s\n", TransactionSynchronizationManager.isActualTransactionActive());
    }
    public void m2() {
        m1();
    }
...
}
...
@Component("frontend")
public class FrontendService {
    @Autowired
    private BackendService back;
    public void test() {
        back.m1();
        back.m2();
        ...
    }
    ...
}

The method m1 is marked with the annotation @Transactional so it should be transactional - right?

Yes and no.

To understand the problem one need to understand how this actually works. The JVM does not do anything with @Transactional - to the JVM then it is just an arbitrary annotation put on a method and the JVM expect the application itself to do whatever is needed for that annotation. In thise case Spring DI (Dependency Injection) is expected to handle it.

    @Autowired
    private BackendService back;

does not do a:

        back = new BackendService();
instead it does a:
        back = new GeneratedSubclassForBackendService();

and transactions work because that one looks like:

...
public class GeneratedSubclassForBackendService extends BackendService {
    public void m1() {
        tx.begin();
        super.m1();
        tx.commit();
    }
    public void m2() {
        super.m2();
    }
}

So when FrontendService.test calls back.m1() then it calls GeneratedSubclassForBackendService.m1 that handle transaction and calls BackendService.m1!

But when BackendService.m2 calls m1 then it just calls BackendService.m1, so no transactional support despite the @Transaction annotation!

Comments: