在事务回滚中添加操作

时间:2013-12-16 19:57:50

标签: java spring transactions spring-transactions

我在应用程序中的事务回滚之前运行一些代码时遇到问题。我想要的是在发生异常时进行回滚,但我还想在表中存储一些关于应用程序状态的信息,包括任何错误或堆栈跟踪。

这是我的代码:

public void performAction(String approverId, Document document, String action) {
        try {
            LOG.info(String.format("routing document %s %s %s", approverId, document.getDocumentId(), action));
            getDocumentService().route(approverId, document, action);
        } catch (Exception e) {
            LOG.error(String.format("error routing document %s %s %s", approverId, document.getDocumentId(), action));
            LOG.error(e, e);
            saveException(document, action, e); //this is what I want
        }
    }

saveException()方法只是创建一个对象并将其保存到表中。

现在根据Spring文档about transactions,默认情况下会发生此回滚,其中异常是运行时异常,并且我已确认回滚正常工作但它不知道我的代码运行并保存我需要的信息或者将那个回滚(?)。

对解决方案的任何帮助或提示表示赞赏。

1 个答案:

答案 0 :(得分:0)

这不是一个不常见的用例:事务失败,我们想将其回滚,但我们仍然希望更新一些监控数据库表,并显示错误原因。

为了在Spring应用程序中执行此操作,请使用REQUIRES_NEW传播@Transactional注释。

@Transactional REQUIRES_NEW propagation

为此,请创建一个应用程序状态跟踪服务,并使用REQUIRES_NEW事务传播对其进行注释。

状态跟踪服务中的每个方法都将在其自己的单独事务中运行,因此当主业务方法上的事务回滚时,状态跟踪信息仍将在数据库上可用。

相关问题