UnexpectedRollbackException:事务已回滚,因为它已标记为仅回滚

Ary*_*rya 33 java spring hibernate transactions

我有这种情况:

  1. IncomingMessage表中获取(读取和删除)记录
  2. 阅读记录内容
  3. 在某些表格中插入内容
  4. 如果在步骤1-3中发生错误(任何异常),则将错误记录插入OutgoingMessage
  5. 否则,将成功记录插入OutgoingMessage

所以步骤1,2,3,4应该在一个交易中,或者步骤1,2,3,5

我的流程从这里开始(这是一个计划任务):

public class ReceiveMessagesJob implements ScheduledJob {
// ...
    @Override
    public void run() {
        try {
            processMessageMediator.processNextRegistrationMessage();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
// ...
}
Run Code Online (Sandbox Code Playgroud)

我在ProcessMessageMediator中的主要功能(processNextRegistrationMessage):

public class ProcessMessageMediatorImpl implements ProcessMessageMediator {
// ...
    @Override
    @Transactional
    public void processNextRegistrationMessage() throws ProcessIncomingMessageException {
        String refrenceId = null;
        MessageTypeEnum registrationMessageType = MessageTypeEnum.REGISTRATION;
        try {
            String messageContent = incomingMessageService.fetchNextMessageContent(registrationMessageType);
            if (messageContent == null) {
                return;
            }
            IncomingXmlModel incomingXmlModel = incomingXmlDeserializer.fromXml(messageContent);
            refrenceId = incomingXmlModel.getRefrenceId();
            if (!StringUtil.hasText(refrenceId)) {
                throw new ProcessIncomingMessageException(
                        "Can not proceed processing incoming-message. refrence-code field is null.");
            }
            sqlCommandHandlerService.persist(incomingXmlModel);
        } catch (Exception e) {
            if (e instanceof ProcessIncomingMessageException) {
                throw (ProcessIncomingMessageException) e;
            }
            e.printStackTrace();
            // send error outgoing-message
            OutgoingXmlModel outgoingXmlModel = new OutgoingXmlModel(refrenceId,
                    ProcessResultStateEnum.FAILED.getCode(), e.getMessage());
            saveOutgoingMessage(outgoingXmlModel, registrationMessageType);
            return;
        }
        // send success outgoing-message
        OutgoingXmlModel outgoingXmlModel = new OutgoingXmlModel(refrenceId, ProcessResultStateEnum.SUCCEED.getCode());
        saveOutgoingMessage(outgoingXmlModel, registrationMessageType);
    }

    private void saveOutgoingMessage(OutgoingXmlModel outgoingXmlModel, MessageTypeEnum messageType)
            throws ProcessIncomingMessageException {
        String xml = outgoingXmlSerializer.toXml(outgoingXmlModel, messageType);
        OutgoingMessageEntity entity = new OutgoingMessageEntity(messageType.getCode(), new Date());
        try {
            outgoingMessageService.save(entity, xml);
        } catch (SaveOutgoingMessageException e) {
            throw new ProcessIncomingMessageException("Can not proceed processing incoming-message.", e);
        }
    }
// ...
}
Run Code Online (Sandbox Code Playgroud)

正如我所说,如果在步骤1-3中发生任何异常,我想插入错误记录:

catch (Exception e) {
    if (e instanceof ProcessIncomingMessageException) {
        throw (ProcessIncomingMessageException) e;
    }
    e.printStackTrace();
    //send error outgoing-message
    OutgoingXmlModel outgoingXmlModel = new OutgoingXmlModel(refrenceId,ProcessResultStateEnum.FAILED.getCode(), e.getMessage());
    saveOutgoingMessage(outgoingXmlModel, registrationMessageType);
    return;
}
Run Code Online (Sandbox Code Playgroud)

它是SqlCommandHandlerServiceImpl.persist()方法:

public class SqlCommandHandlerServiceImpl implements SqlCommandHandlerService {
// ...
    @Override
    @Transactional
    public void persist(IncomingXmlModel incomingXmlModel) {
        Collections.sort(incomingXmlModel.getTables());
        List<ParametricQuery> queries = generateSqlQueries(incomingXmlModel.getTables());
        for (ParametricQuery query : queries) {
            queryExecuter.executeQuery(query);
        }
    }
// ...
}
Run Code Online (Sandbox Code Playgroud)

但是当sqlCommandHandlerService.persist()抛出异常(这里是org.hibernate.exception.ConstraintViolationException异常)时,在OutgoingMessage表中插入错误记录后,当事务想要提交时,我得到UnexpectedRollbackException.我无法弄清楚我的问题在哪里:

Exception in thread "null#0" org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:717)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:394)
    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:622)
    at ir.tamin.branch.insuranceregistration.services.schedular.ReceiveMessagesJob$$EnhancerByCGLIB$$63524c6b.run(<generated>)
    at ir.asta.wise.core.util.timer.JobScheduler$ScheduledJobThread.run(JobScheduler.java:132)
Run Code Online (Sandbox Code Playgroud)

我正在使用hibernate-4.1.0-Final,我的数据库是oracle,这是我的事务管理器bean:

<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager"
    proxy-target-class="true" />
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Ean*_*n V 43

这是正常行为,原因是您的sqlCommandHandlerService.persist方法在执行时需要TX(因为它标有@Transactional注释).但是当它在内部调用时processNextRegistrationMessage,因为有可用的TX,容器不会创建新的并使用现有的TX.因此,如果sqlCommandHandlerService.persist方法中发生任何异常,则会将TX设置为rollBackOnly(即使您在调用者中捕获异常并忽略它).

要解决此问题,您可以使用传播级别进行事务处理 看看这个,找出最适合您需求的传播方式.

更新; 读这个!

在一位同事带着几个关于类似情况的问题来找我之后,我觉得这需要一些澄清.
虽然传播解决了这些问题,但是你应该非常小心地使用它们,除非你绝对理解它们的含义和工作方式,否则不要使用它们.你最终可能会持久保存一些数据并回滚其他一些你不希望它们以这种方式工作的东西,而且事情可能会出现严重错误.


编辑 链接到当前版本的文档

  • 这两者之间的区别在于,NESTED就像一个子TX,所以如果父提交,它将被提交,否则不会.REQUIRES_NEW创建一个新TX并暂停现有TX.所以它会单独提交.请注意您的容器,因为所有容器都不支持这些容器.上面的链接对支持这些类型的传播的环境有一些解释. (5认同)

小智 5

Shyam的回答是正确的。我以前已经遇到过这个问题。这不是问题,这是SPRING功能。可以接受“事务已回滚,因为它已被标记为仅回滚”。

结论

  • 如果您想提交在异常之前所做的操作(本地提交),请使用REQUIRES_NEW
  • 如果只想在所有进程完成后才提交(全局提交),则需要使用,而您只需要忽略“事务回滚,因为它已被标记为仅回滚”例外。但是您需要尝试将调用者processNextRegistrationMessage()排除在外,以获取含义日志。

让我解释更多细节:

问题:我们有多少笔交易?Anser:只有一个

因为配置了PROPAGATION,所以PROPAGATION是PROPAGATION_REQUIRED,以便@Transactionpersist()与调用方processNextRegistrationMessage()使用同一事务。实际上,当我们收到异常时,Spring将为TransactionManager 设置rollBackOnly,因此Spring仅回滚一个Transaction。

问题:但是我们在()之外有一个try-catch,为什么会发生此异常?回答由于独特的交易

  1. 当persist()方法有异常时
  2. 去外面的地方

    Spring will set the rollBackOnly to true -> it determine we must 
    rollback the caller (processNextRegistrationMessage) also.
    
    Run Code Online (Sandbox Code Playgroud)
  3. persist()将首先回滚自身。

  4. 抛出UnexpectedRollbackException来通知我们,我们还需要回滚调用方。
  5. run()中的try-catch将捕获UnexpectedRollbackException并打印堆栈跟踪

问题:为什么我们将PROPAGATION更改为REQUIRES_NEW,这行得通?

答案:因为现在processNextRegistrationMessage()和persist()位于不同的事务中,因此它们仅回滚其事务。

谢谢