Understanding Spring transactions - What happens when a transactional method calls another transactional method?

后端 未结 1 580
别那么骄傲
别那么骄傲 2020-12-01 01:27

Just to understand the workings of Spring transactions I want to know what happens in the following case where one method marked as @Transactional calls another

相关标签:
1条回答
  • 2020-12-01 02:10

    Two answers:

    a) don't do it. Use @Transactional in the service layer or the dao layer, but not both (the service layer is the usual choice, as you probably want one transaction per service method)

    b) if you do it, what happens depends on the propagation attribute of the @Transactional annotation and is described in this section: 10.5.7 Transaction propagation. Basically: PROPAGATION_REQUIRED means the same transaction will be used for both methods, while PROPAGATION_REQUIRES_NEW starts a new transaction.

    About your comments:

    Of course I kept reading and realized that, as I'm using proxies, this second method won't be managed by the transactional proxy, thus it's like any other method call.

    That's not true in your situation (only if both methods were within the same class).

    If a bean has methods a and b, and a calls b, then b is called on the actual method, not the proxy, because it is called from within the proxy (a bean doesn't know that it is proxied to the outside world).

    proxy      bean  
    a() -->    a()
                |
                V  
    b() -->    b()
    

    In your situation, however, a service would have an injected dao object, which would be a proxy itself, so you'd have a situation like this:

               proxy      bean
    service    a() -->    a()
                           |
                 /---------/
                 |                 
                 V
    dao        b() -->    b()
    
    0 讨论(0)
提交回复
热议问题