2015-03-13 53 views
0

這是我的代碼的一部分。我正在使用JTA事務,這段代碼拋出了唯一的約束異常。如何做容器管理的JTA事務中的異常處理

@TransactionAttribute(REQUIRED) 
      private int createProfileHelper(AccountBean accountInfo) throws Exception{  
     Long portfolio_customer_id = portfolioCustomerEntity.getId(); 
          ExternalAccountEntity externalAccountEntity = new ExternalAccountEntity(); 
          externalAccountEntity.setAccountNumber(accountInfo.getAccountNumber().toUpperCase()); 
          externalAccountEntity.setBrand(brand); 
          externalAccountEntity.setAccountName(accountInfo.getAccountName()); 
          externalAccountEntity.setRepId(accountInfo.getRepId()); 
          externalAccountEntity.setCreatedBy(userName); 
          externalAccountEntity.setCreatedDate(new Date()); 
          externalAccountEntity.setUserId(userId); 
          externalAccountEntity.setCustomerId(portfolio_customer_id); //join created between external account and portfolio_customer 
          persistenceToolsEntityManager.persist(externalAccountEntity); 
    } 

我寫了這個代碼來處理異常:

public int createProfile(AccountBean accountInfo){ 
     try{ 
      return createProfileHelper(accountInfo); 
     }catch(Exception e){ 
      logger.error(e); 
      logger.error(e.getMessage()); 
      return 0; 
     } 
    } 

令我驚訝,我不能趕上我try catch塊例外,雖然我可以看到除了在服務器上閃爍:

Mar 13, 2015 9:19:58 AM org.apache.geronimo.transaction.manager.TransactionImpl beforeCompletion 
WARNING: Unexpected exception from beforeCompletion; transaction will roll back 
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException 
Internal Exception: java.sql.SQLException: ORA-00001: unique constraint (SEC.PORTFOLIO_EXTERNAL_ACCOUNT_U1) violated 
+0

我認爲異常仍然被捕獲,儘管事務正在回滾。你確定不是這樣嗎? – Magnilex 2015-03-13 13:44:06

+0

是的:(我在catch裏面放了一個斷點,我無法打到它 – JackSparrow 2015-03-13 13:49:48

回答

0

真的不是那麼棒。

您的@TransactionAttribute(REQUIRED)實際上沒有任何效果。此註釋只能應用於公共方法,並且只有在從其他bean調用時才具有效果。換句話說,您不能使用批註在同一個bean中的方法調用之間劃分事務。

javax.persistence.PersistenceException已退出createProfile方法(默認情況下具有隱式@TransactionAttribute(REQUIRED))時被事務管理器困住。

+0

以前我從來沒有創建過一個私有方法,我只是創建了它,以便通過具有@TransactionAttribute(REQUIRED)的公共方法來捕獲異常。我怎樣才能讓我的多個數據庫調用作爲一個單獨的事務?...這個公共方法由一個其他調用調用。 – JackSparrow 2015-03-13 14:03:25

+0

在REST處理程序中捕獲異常。即調用'createProfile' – 2015-03-13 21:47:20

0

嘗試在persistenceToolsEntityManager.persist上放置斷點並逐行放入代碼中。
你會發現org.apache.geronimo.transaction.manager.TransactionImpl爲你處理異常。
如果您想在發生任何異常時執行其他操作,請嘗試使用TransactionManagergetStatus()
:)