1

This question comes from that, if I have a methodA, and methodB in classA like below

public class classA {
    public void methodA() {
        // some code
        ...

        // time to deal with db
        methodB();
    }

    @Transactional
    public void methodB() {
        // insert a record 

        throw new RuntimeException("testing");
    }
}

In classB Directly call methodA, there will be no transactional effect on methodB(this is to say spring will not rollback the insert operation even RuntimeException occurred).

When I move the @Transactional from methodB to methodA, and call methodA again, the @Transactional annotation works.

However, if I have really a lot of work to do in methodA, will spring lock the table during the total execution time?

xuanzhui
  • 1,300
  • 4
  • 12
  • 30

2 Answers2

0

Well, I will add a new class(i.e. classC) and move methodB(annotated with Transactional) to the new class as workaround.

It is the limitation of Springs AOP that @Transactional will not have effect if the method is called within the same class.
Refer to @Transactional method called from another method doesn't obtain a transaction

xuanzhui
  • 1,300
  • 4
  • 12
  • 30
0

Spring doesn't handle transaction by itself. @Transactional annotation lets Spring's proxy class to inject transaction begin and commit/rollback methods around your original method.

  • Proxy wrapper will only be called if you invoke annotated method from outside the classes. Local method call will not use proxy class. So, call from method A to method B will not use transactional features.
  • Secondly, Spring will simply delegate the transaction handling to underlying database driver. Whether your table acquires a lock or not will be determined by your driver documentation and (atomicity and isolation level) settings.
Bipul
  • 1,564
  • 1
  • 15
  • 16