What data is stored in the transaction?

What data is stored in @Transactional services, especially in a transaction? If I have a controller layout, a services layout, Taoism and a database - why should I use my services with @Transactional annotation and what data is stored between these layouts? For example, I send some data to an object, and I want it to write to the database. Well, will all this data be stored in a transaction? But what if I only update some data in the database, giving also the identifier of the object? Can you help me figure this out?

0
source share
1 answer

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:

//Controller method { //... accountA.setValue(accountA.getValue() - amount); accountService.update(accountA); accountB.setValue(accountB.getValue() + amount); accountService.update(accountB); } 

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.

+2
source

Source: https://habr.com/ru/post/988579/


All Articles