简体   繁体   中英

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

I have a Spring+JPA application. 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). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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