@Transactional(propagation = Propagation.REQUIRED)

2019-08-20 02:43发布

If I have the following code :

@Component
public class A{ 

@Transactional(propagation = Propagation.REQUIRED)
public void a(){
    //logic
    b();
 //logic
}

@Transactional(propagation = Propagation.REQUIRED)
public void b(){
    //logic
} 
}

How many transactions open Spring in this code example?

4条回答
萌系小妹纸
2楼-- · 2019-08-20 03:06

From spring documentation: https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/transaction/annotation/Propagation.html

REQUIRED: Support a current transaction, create a new one if none exists

It only creates one transaction.

查看更多
Bombasti
3楼-- · 2019-08-20 03:08

Refering to the documentation Propagation.REQUIREDsupport a current transaction, create a new one if none exists. The answer to your question is :

1 transaction, if there is no transaction when A#a() is called.

0- zero if there is already one because it will be reused.

查看更多
一夜七次
4楼-- · 2019-08-20 03:16

It doesn't matter. When calling b() from a() it won't be going through the proxy, so any transactional attributes on b() won't be considered.

The example code has 1 transaction open if a() or b() is called through the proxy (i.e. outside of the class) and there isn't a transaction in progress already.

查看更多
forever°为你锁心
5楼-- · 2019-08-20 03:26

I add to @pablo answer the notice that in your example you cannot see the actual difference because your call your method within the same object which make @transaction behavior on the second method transparent with no effect :

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

查看更多
登录 后发表回答