Зміст курсу
Spring Boot Backend
Spring Boot Backend
Transactions
A transaction essentially gives us a choice: either all the operations within it are completed successfully, or none of them are executed at all.
Imagine a bank transfer operation, where money is moved from one account to another. This process involves two steps:
- Deducting money from one account;
- Depositing money into another account.
If the transaction fails after deducting money but before depositing it, the funds could be "lost." A transaction ensures that both operations are either fully completed or fully reversed.
Basics of Transaction Management
The @Transactional
annotation: This is used to declare methods or classes that should be executed within the context of a transaction.
When a method with this annotation is called, Spring starts a new transaction. If the method completes successfully, the transaction is committed; otherwise, it is rolled back.
Let’s provide an example based on the real-life scenario mentioned earlier.
BankService
@Service public class BankService { private AccountRepository accountRepository; @Transactional public void transferMoney(Long fromAccountId, Long toAccountId, double amount) { Account fromAccount = accountRepository.findById(fromAccountId); Account toAccount = accountRepository.findById(toAccountId); fromAccount.withdraw(amount); toAccount.deposit(amount); accountRepository.save(fromAccount); accountRepository.save(toAccount); } }
When the transferMoney
method is marked with the @Transactional
annotation, it means that all changes happening within this method will be executed within a single transaction.
When we call fromAccount.withdraw(amount)
followed by toAccount.deposit(amount)
, both of these actions must be successfully completed. If, for instance, an error occurs during the toAccount.deposit(amount)
operation, the transaction will automatically roll back the changes made during the fromAccount.withdraw(amount)
step.
This ensures that either both operations are executed and the money is transferred, or, in the event of an error, neither operation is performed, preventing any loss of funds. The transaction guarantees that the database will never be left in an inconsistent state.
Practical Application of Transactions
Summary
A transaction is a set of database operations treated as a single unit, ensuring all operations succeed together or are fully rolled back in case of failure. You can learn more about transactions here.
Дякуємо за ваш відгук!