2016-05-23 64 views
0

我得到了這段代碼。我使用的彈簧引導和JPA如何處理彈簧jpa @transactional和從catch塊新插入

@Transactional 

public class MyClass { 

    public void createSomething() { 
     try { 
      saveAndFlush(); 
     } catch (Exception e) { 
      // Since error has occured I want to insert this information 
      // into a audit table 

      repository.saveAndFlush(); 

     } 
    } 

} 

現在,當異常發生時,事務回滾,因此錯誤表插入沒有發生。

我看到

HHH000099: an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): org.hibernate.AssertionFailure: null id in XXXXX entry (don't flush the Session after an exception occurs) 

爲了解決這個問題我試着做了錯誤插入在理解打上@Transactional(propagation = Propagation.REQUIRES_NEW),內部交易將完成與外將回滾

的新方法

但我沒有看到我的預期輸出。

請告知

+0

正確。這確實是一個重複 – Shiv

+0

@阿蘭乾草 - 即使按照原始線程中的說明,我仍然看到相同的問題。我將其作爲個別方法中的交易,並添加了一個需要新的傳播 – Shiv

回答

1

取下一流水平的@Transactional,並用它在那些實際執行的交易方法。 (如果你在該課程中有超過1種方法,當然)。

如果您希望獨立事務提交/回滾到數據庫,則在不會干擾全局事務的方法上使用REQUIRES_NEW傳播。

未提及任何傳播的'@Transactional'的默認行爲是,加入全局(調用)事務(如果有),並且如果不啓動新事務。

由於您有一個全局事務,它將完全回退。相反,您需要獨立交易。

+0

我將其作爲單個交易,但仍然沒有看到它的工作。 – Shiv