交易中存储什么数据? [英] What data is stored in transaction?

查看:100
本文介绍了交易中存储什么数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪些数据存储在@Transactional服务中,尤其是在事务中?如果我有一个控制器布局,服务布局,dao和数据库-为什么我必须将我的服务与@Transactional批注一起使用,以及在这些布局之间存储哪些数据?
例如,我发送一些对象数据并将其写入数据库。好了,在交易中会存储所有这些数据吗?但是,如果我仅通过给出对​​象的ID和ID更新数据库中的某些数据,该怎么办?
您能帮助我理解吗?

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?

推荐答案

这与存储事务中的数据无关。这是关于一次交易中执行一些操作的问题。

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

想象一下您创建了银行系统,并且您有进行汇款的方法。假设您要将金额从帐户A转移到帐户B

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);
}

但是这种方法存在一些严重的问题。即,如果对帐户A的更新操作成功但对帐户B的更新失败,该怎么办?钱会消失。一个帐户丢失了它,但是第二个帐户没有得到它。

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);
}

此方法用@Transactional标记,这意味着任何失败都会导致整个操作回滚到以前的状态。因此,如果更新之一失败,则对数据库的其他操作将被回滚。

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.

这篇关于交易中存储什么数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆