@Transactional 方法调用同一类中的方法。

huangapple go评论52阅读模式
英文:

@Transactional method calling a method in the same class

问题

我有一个名为UserService的类,其中有一个名为saveUser()和saveAmount()的方法,如下所示。

class UserService {

@Transactional
public void saveUsers() {
    将saveUser1保存到数据库;
    将saveUser2保存到数据库;
    保存金额();
    将saveUser3保存到数据库;
}

public void saveAmount() {
    将saveAmount1保存到数据库;
    将saveAmount2保存到数据库 // 抛出异常
    将saveAmount3保存到数据库;
}

}


根据Spring AOP的规定,当调用saveAmount()时,不会触发代理,我们将继续使用saveUsers方法的同一事务进行saveAmount,因此如果saveAmount中发生任何异常(比如在方法的第2行),将回滚saveUser1到数据库和saveUser2到数据库。

问题: saveAmount1保存到数据库也会被回滚吗?


我尝试在我的本地机器上复制此操作,并且我预计saveAmount1保存到数据库不会回滚,因为它是从同一对象调用的,AOP没有启动。
英文:

I have a class UserService which has a method saveUser() and saveAmount() as shown below.

class UserService {
    
    @Transactional
    public void saveUsers() {
        saveUser1 to db;
        saveUser2 to db;
        saveAmount();
        saveUser3 to db;
    }
    
    public void saveAmount() {
        saveAmount1 to db;
        saveAmount2 to db // throws exception
        saveAmount3 to db;
    }
}

As per Spring AOP, when saveAmount() is called, the proxy won't be triggered and we have the same transaction of saveUsers method continuing with saveAmount, so any exception in saveAmount (say in line 2 of the method) if occured will rollback saveUser1 to db and saveUser2 to db.

Question : Will saveAmount1 to db be rolled back as well ?

I tried replicating this on my local machine and I am expecting that saveAmount1 to db won't rollback as it was called from them same object and AOP did not kick in.

答案1

得分: 2

AOP 不会触发它,如果你是自我调用一个带 @Transactional 标记的方法,这仅意味着被自我调用的方法上的 @Transactional 将不会起作用。

但现在 saveAmount() 上没有任何 @Transactional 注解,所以它与 AOP 是否会触发无关。

在这种情况下,saveUsers()saveAmount() 都在同一个事务中执行。同一事务中的所有代码都具有全体或无效行为,这意味着对数据库的更改要么全部成功,要么全部失败。全部失败还意味着任何抛出异常的代码将回滚所有成功执行的数据库更改,包括 saveAmount1

英文:

AOP does not kick it if you are self invoking a @Transactional method only means the @Transactional on the method that is being self-invoked will not have any effect.

But now saveAmount() does not have any @Transactional annotated on it , so it is nothing to do with whether the AOP will kick in or not.

In this case , both saveUsers() and saveAmount() execute in the same transaction. All codes in the same transaction has all or nothing behaviour meaning the changes to DB are either all success or all fail. All fail also imply that any codes that throw exception will rollback all DB changes that are executed successfully. So if saveAmount2 throws exception , every DB changes will rollback including saveAmount1.

huangapple
  • 本文由 发表于 2023年6月11日 21:41:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76450749.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定