这与事务中存储的数据无关。这是关于在一个事务中运行一些操作。
假设您创建了银行系统,并且您有进行汇款的方法。假设您想将金额从 accountA 转移到 accountB
您可以在控制器中尝试类似的操作:
//Controller method
{
//...
accountA.setValue(accountA.getValue() - amount);
accountService.update(accountA);
accountB.setValue(accountB.getValue() + amount);
accountService.update(accountB);
}
但是这种方法有一些严重的问题。即如果 accountA 的更新操作成功但 accountB 的更新失败怎么办?钱会消失。一个帐户丢失了它,但第二个帐户没有得到它。
这就是为什么我们应该在服务方法中的一个事务中进行两个操作,如下所示:
//This time in Controller we just call service method
accountService.transferMoney(accountA, accountB, amount)
//Service method
@Transactional
public void transferMoney(Account from, Account to, amount)
{
from.setValue(from.getValue() - amount);
accountRepository.update(from);
to.setValue(to.getValue() + amount);
accountRepository.update(to);
}
此方法带有@Transactional 标记,这意味着任何失败都会导致整个操作回滚到之前的状态。因此,如果其中一个更新失败,数据库上的其他操作将被回滚。