Reputation: 167
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?
Upvotes: 0
Views: 325
Reputation: 5546
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.
Upvotes: 1