@Transactional注释可以与saveAndFlush一起使用吗? [英] @Transactional annotation works with saveAndFlush?
问题描述
我有以下实现.
@Transactional
public void saveAndGenerateResult(Data data) {
saveDataInTableA(data.someAmountForA);
saveDataInTableB(data.someAmountForB);
callAnAggregatedFunction(data);
}
public void saveDataInTableA(DataA a) {
tableARepository.saveAndFlush(a);
}
public void saveDataInTableA(DataB b) {
tableBRepository.saveAndFlush(b);
}
public void callAnAggregatedFunction() {
// Do something based on the data saved from the beginning in Table A and Table B
}
使用saveAndFlush
使数据立即可用于callAnAggregatedFunction
函数以获取汇总结果并将其保存到另一个表中,这一点很重要.这就是为什么我不使用save
函数,据我所知,该函数不会立即将事务刷新到数据库中.
It is important to use saveAndFlush
to have the data immediately available to the callAnAggregatedFunction
function to get an aggregated result and save it to another table. That is why I am not using save
function which does not flush the transactions into database immediately as far as I know.
但是,我要在功能saveAndGenerateResult
上使用@Transactional
批注,因为在发生任何故障(通常通过使用@Transactional
确保)的情况下,我想回退在该功能中完成的数据库事务在方法上的注释.
However, I am using a @Transactional
annotation over the function saveAndGenerateResult
, as I want to rollback the database transactions that I have done in that function in case of any failure which is normally ensured by having a @Transactional
annotation over a method.
在这种特定情况下会发生什么情况?我正在使用saveAndFlush
将数据立即刷新到数据库表中,并且如果最后一个函数(即callAnAggregatedFunction
)无法将数据写入表中,是否会回滚表A和表B中的先前写入操作?
What will be the scenario in this specific case? I am using saveAndFlush
which flushes the data immediately into the database table and if the last function (i.e. callAnAggregatedFunction
) fails to write the data into the table, will the previous write operations in table A and table B will be rollbacked?
推荐答案
是否会回退表A和表B中的先前写操作?
Will the previous write operations in table A and table B be rollbacked?
是的,除非您的saveAndFlush()
方法具有自己的事务(即使用propagation = REQUIRES_NEW
).
Yes, unless your saveAndFlush()
methods have their own transactions (i.e. with propagation = REQUIRES_NEW
).
如果它们都是您在saveAndGenerateResult()
中启动的事务的一部分,则对数据库所做的所有修改将在失败的情况下回滚.
If they're all part of the transaction you started in saveAndGenerateResult()
, all modifications made to the database will be rolled back in case of failure.
有关更多信息: Spring-@Transactional-后台会发生什么?
这篇关于@Transactional注释可以与saveAndFlush一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!