jpa事务停止回滚

时间:2012-02-10 01:49:11

标签: spring 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

2 个答案:

答案 0 :(得分:1)

来自the documentation

  

如果Session抛出异常,包括任何SQLException,   立即回滚数据库事务,调用Session.close()   并丢弃Session实例。 Session的某些方法不会   使会话保持一致状态。没有例外   Hibernate可以被视为可恢复的。确保会话将   通过在finally块中调用close()来关闭。

交易必须回滚。因此,如果要在Hibernate抛出异常时继续执行,则应使用executeQuery注释中的REQUIRES_NEW传播将执行@Transactional方法放入其自己的事务中。这样,只会回滚此短事务。

答案 1 :(得分:-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
}