@Transactional annotation works with saveAndFlush?

ε祈祈猫儿з 提交于 2020-06-24 22:26:20

问题


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. That is why I am not using save function which does not flush the transactions into database immediately as far as I know.

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.

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?


回答1:


Will the previous write operations in table A and table B be rollbacked?

Yes, unless your saveAndFlush() methods have their own transactions (i.e. with 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.

For more information: Spring - @Transactional - What happens in background?

Spring @Transactional - isolation, propagation



来源:https://stackoverflow.com/questions/49855138/transactional-annotation-works-with-saveandflush

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!