本文介绍了jpa事务停止回滚的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码.我希望即使有异常也可以继续执行

I have the following code. I want the execution to continue even if there is an exception

@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();
    }
}

我收到的异常堆栈跟踪是

The exception stack trace that I receive is

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

推荐答案

来自文档:

交易必须必须回滚.因此,如果要在Hibernate引发异常时继续执行,则应使用@Transactional批注中的REQUIRES_NEW传播,将执行executeQuery方法放入其自己的事务中.这样,仅此短事务将被回滚.

The transaction must be rolled back. So, if you want to continue executing if Hibernate throws an exception, you should put the execute the executeQuery method in its own transaction, using the REQUIRES_NEW propagation in the @Transactional annotation. This way, only this short transaction will be rolled back.

这篇关于jpa事务停止回滚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-10 22:31