2012-02-10 101 views
1

我有下面的代碼。我希望繼續執行,即使有異常JPA事務回滾停止

@Transactional(noRollbackFor={PersistenceException.class, PSQLException.class,SQLGrammarException.class}) 
public void executeQuery(String parameterName){ 
    Query query = objectManager.getEntityManager().createNativeQuery("SOME UPDATE QUERY"); 

    Map<String, String> paramMap = (Map) destTableMap.get(parameterName); 
    query.setParameter("xyz",5); 

    try{ 
     query.executeUpdate(); 
    }catch(Exception ex){ 
     ex.printStackTrace(); 
    } 
} 

,我收到是

Exception in thread "main" org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly 
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:476) 
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754) 
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723) 
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393) 
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120) 
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) 
    at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:621) 
    at 
Caused by: javax.persistence.RollbackException: Transaction marked as rollbackOnly 
    at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:73) 
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:467) 
    ... 11 more 
+0

重複:http://stackoverflow.com/questions/1701750/how-to-prevent-jpa - 從軋回事務 – 2012-02-10 08:53:15

回答

1

the documentation的異常堆棧跟蹤:

如果Session拋出異常,包括任何的SQLException, 立即回滾數據庫事務,調用Session.close() ,丟棄該Session實例。會話的某些方法不會 使會話保持一致狀態。 沒有拋出異常Hibernate可以被視爲可恢復。通過在finally塊中調用close()來確保會話將會關閉 。

交易必須回滾。所以,如果你想繼續執行,如果休眠拋出一個異常,你應該把在自己的事務的執行executeQuery方法,使用REQUIRES_NEW傳播的@Transactional註解。這樣,只有這個短交易會被回滾。

-1

我嘗試使用以下方法來避免這種TransactionSystemException: org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction;嵌套的例外是javax.persistence.RollbackException:事務標記爲rollbackOnly

@Transactional(readOnly = false, rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW) 
public String foo(Object obj, String tableName, BindingResult result) throws Exception 
{ 
    // put some code here 
}