简体   繁体   English

将来引发异常时如何回滚事务?

[英]How can I rollback transaction when throwing an exception in future?

I have a Spring+JPA application. 我有一个Spring + JPA应用程序。 My service does some database persistence operations and async long calculations: 我的服务执行一些数据库持久性操作和异步长计算:

@Transactional(rollbackFor = Exception.class)
public MyEntity execute(MyEntity entity) {
    //database operations
    em.persist(entity);

    Executors.newSingleThreadExecutor().submit(() -> {
        //long calculations
        if (errorOccurs)
            throw new RuntimeException("Rollback transaction");
    });

    return entity;
}

I want to rollback database changes when an exception occurs in future. 我想在将来发生异常时回滚数据库更改。 How can I do it? 我该怎么做?

This looks like DAO class (Data Access Object). 看起来像DAO类(数据访问对象)。 Generally, you want to keep a DB connection or transaction open as short as you can, so this looks like a bad idea. 通常,您希望保持数据库连接或事务的打开时间尽可能短,所以这似乎是个坏主意。

I don't know what is that long calculation of yours, but I'd make it before you persist the entity. 我不知道您的冗长计算时间是多少,但我会在您保留实体之前进行计算。

Asynchronous and potentially parallel computation can be very useful, but here I see more dangers than benefits, and you'll leave a DB transaction hanging for quite some time if you wait for completion. 异步和潜在的并行计算可能非常有用,但是在这里,我看到的是弊大于利,如果等待完成,您将使数据库事务挂起相当长的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM