This is not about saved data in a transaction. Its launch of some operations in one transaction.
Imagine that you are creating a banking system and you have a way to make money transfers. Suppose you want to transfer the amount of money from account A to account B
You can try sth like this in the controller:
But this approach has some serious problems. Namely, what to do if the update operation for the account is successful, but the update for accountB is not performed? Money will disappear. One account lost it, but the second account did not receive it.
This is why we must do both operations in the same transaction in the sth service method as follows:
//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); }
This method is marked with @Transactional, which means that any failure causes the entire operation to roll back to its previous state. Thus, if one of the updates fails, other database operations will be copied.
source share