简体   繁体   中英

Transactional method called by method in same class called from another class

I have a transactional method that is called called multiple time (in a loop) by a method in the same class. This method in the same class is called by a method in a different class. From my investigation, when we call a transaction method within the same class, this has no effect. The same transaction is used. But in my case, will a new transaction be used?

Structure:

A.class - Method A
                 |-> B.class - Method A
                                      |-> call mutiple times - B.class - @Transactional Method B

Can you advise?

My expectations is that a new transaction on Method B is created each time I loop through it. Do I need to pass the Method B to a different class? Or it will start a new transaction every time?

So BY DEFAULT two things are potentially working against you.

Spring's default txn interceptors, which is how AOP transactions work, will not pick up calls within the same instance. This can be changed by switching to AspectJ weaving. This article has a good explanation https://www.baeldung.com/spring-aop-vs-aspectj IIRC the default in spring is jdk proxying.

Spring's default transactional annotation will propagate existing txns. So if there's not a pre-existing txn AND you overcome the above you should get what you want. If there's a pre-existing txn, it will by default be used, but this behaviour can be changed by modifying the propagate parameter on your @Transactional annotation. This article has a good explanation: https://www.baeldung.com/spring-transactional-propagation-isolation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM