What data is stored in transaction?

2019-08-30 04:13发布

问题:

Which data is stored in @Transactional services, especially in the transaction? If I have a controllers layout, services layout, daos and database - why I have to use my services with @Transactional annotation and what data is stored between these layouts? For example, I send some object data and I want it write to database. Well, in the transaction will be stored all this data? But what if I only update some data in database by giving and id of the object? Can you help me understand it?

回答1:

It's not about stored data in transaction. It's about running some operations in one transaction.

Imagine that you create banking system, and you have method for making money transfer. Let's assume that you want to transfer amount of money from accountA to accountB

You can try something like that in controller:

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

accountB.setValue(accountB.getValue() + amount);
accountService.update(accountB);
}

But this approach have some serious problems. Namely what if update operation for accountA succeed but update for accountB fail? Money will disappear. One account lost it but second account didn't get it.

That's why we should make both operations in one transaction in service method something like this:

//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 tagged with @Transactional, meaning that any failure causes the entire operation to roll back to its previous state. So if one of updates fail, other operations on database will be rolled back.