簡體   English   中英

手動事務回滾限制到 Spring boot 中 forEach 循環中的單個迭代

[英]Manual transactional rollback bounds to an individual iteration in a forEach loop in Spring boot

我正在嘗試更新表中的幾列,並且更新發生在forEach內。

我想將每個迭代作為一個單獨的事務處理,並且 forEach 內的任何回滾都應該只回滾在特定迭代(而不是所有以前的迭代)上發生的事務。

此外,我不希望異常觸發回滾。 相反,它必須以編程方式觸發。 為此,我正在使用這個 - TransactionInterceptor.currentTransactionStatus().setRollbackOnly();

到目前為止,這是我嘗試過的:

@Service
public class MyService {
    @Transactional
    public void processLabResults() {
        arrayList.forEach(i -> {
            proccessDiagnosis();
        });
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    proccessDiagnosis() {
        boolean isDispositionUpdated = updateDisposition(); // calls JPA Repository to update
        if(isUpdated) {
            boolean isSomethingElseUpdated = updatedSomethingElse(); // calls JPA Repository to update
            if(!isSomethingElseUpdated) {
                TransactionInterceptor.currentTransactionStatus().setRollbackOnly(); //Should rollback only the transactions that happened in the current iteration
            }
        }
    }
}

如果我執行上面的操作,它也會回滾所有不屬於當前迭代的先前事務。 如果我從@ Transactional方法中刪除processLabResults批注,我將收到No transaction aspect-managed TransactionStatus in scope錯誤並且不會發生回滾。

任何幫助,將不勝感激。 謝謝!

這個答案幫助我解決了這個問題。 我將proccessDiagnosis()函數移動到不同的服務文件。

服務.java

@Service
public class MyService {

    @AutoWired
    AnotherService anotherService;

    @Transactional
    public void processLabResults() {
        arrayList.forEach(i -> {
            anotherService.proccessDiagnosis();
        });
    }
}

另一個服務.java

@Service
public class AnotherService {
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void proccessDiagnosis() {
        boolean isDispositionUpdated = updateDisposition(); // calls JPA Repository to update
        if(isUpdated) {
            boolean isSomethingElseUpdated = updatedSomethingElse(); // calls JPA Repository to update
            if(!isSomethingElseUpdated) {
                TransactionInterceptor.currentTransactionStatus().setRollbackOnly(); //Should rollback only the transactions that happened in the current iteration
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM