Spring @Transactional Annotation : Self Invocation

前端 未结 2 856
半阙折子戏
半阙折子戏 2020-12-09 11:44

I know when a transactional method is called from inside the same class it wouldn\'t be run in a transaction. Spring creates a proxy for transactional methods and wraps them

相关标签:
2条回答
  • 2020-12-09 11:45

    If you call saveAB and saveB throws an Exception, your transaction will rollback.

    Self-invocation doesn't break the transnational context. It just not starts one if nk contdxt id available.

    0 讨论(0)
  • 2020-12-09 12:01

    What I don't understand is why do people say self invocation breaks transaction?

    I never heard that self-invocation breaks transaction. All I know is that self-invocation will not start a new transaction and you already mentioned the reason why.

    Snippet from Spring's Transaction Management Specification

    Note In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional.


    If you remove @Transaction annotation from saveAB(), you would observe that method saveA() and saveB() would not run under transaction even though it is annotated with @Transactional. However, if you call saveA() or saveB() from outside the class, it will run under transaction as expected. That is the reason why people advice to be cautious with self-invocation.

    public void saveAB(A a, B b)
    {
        saveA(a);
        saveB(b);
    }
    
    @Transactional
    public void saveA(A a)
    {
        dao.saveA(a);
    }
    
    @Transactional
    public void saveB(B b)
    {
        dao.saveB(b);
    }
    

    In my view, self-invoking any public method is a bad idea.

    0 讨论(0)
提交回复
热议问题