简体   繁体   English

@Transactional注释与saveAndFlush一起使用?

[英]@Transactional annotation works with saveAndFlush?

I have the following implementation. 我有以下实现。

@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
}

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. 使用saveAndFlush使callAnAggregatedFunction函数可以立即获得数据以获取聚合结果并将其保存到另一个表非常重要。 That is why I am not using save function which does not flush the transactions into database immediately as far as I know. 这就是为什么我没有使用save函数,据我所知,它不会立即将事务刷新到数据库中。

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. 但是,我在函数saveAndGenerateResult使用@Transactional注释,因为我想回滚我在该函数中完成的数据库事务,以防任何故障通常通过对方法进行@Transactional注释来确保。

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 (ie callAnAggregatedFunction ) fails to write the data into the table, will the previous write operations in table A and table B will be rollbacked? 我正在使用saveAndFlush将数据立即刷新到数据库表中,如果最后一个函数(即callAnAggregatedFunction )无法将数据写入表中,那么表A和表B中的先前写操作是否会被回滚?

Will the previous write operations in table A and table B be rollbacked? 表A和表B中的先前写操作是否会被回滚?

Yes, unless your saveAndFlush() methods have their own transactions (ie with propagation = REQUIRES_NEW ). 是的,除非你的saveAndFlush()方法有自己的事务(即propagation = REQUIRES_NEW )。

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. 如果它们是您在saveAndGenerateResult()启动的事务的全部内容,则在发生故障时将回滚对数据库所做的所有修改。

For more information: Spring - @Transactional - What happens in background? 有关更多信息: Spring - @Transactional - 后台会发生什么?

Spring @Transactional - isolation, propagation Spring @Transactional - 隔离,传播

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM