简体   繁体   中英

@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. 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 (ie callAnAggregatedFunction ) fails to write the data into the table, will the previous write operations in table A and table B will be rollbacked?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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