@Transactional annotation works with saveAndFlush?

2020-07-06 05:06发布

问题:

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