Reputation: 589
I'm working on rather simple RESTful service based on SpringBoot. I'm using Ebean and SpringData. All my REST methods are annotated with @Transactional:
@Transactional
@PostMapping
public Entity createEntity(...) {
// some code
}
The problem I'm facing is that if there is a network issue but this method executes without an exception, the transaction will still get committed. For example, the client might send the data, my code creates the record but then the server can't send a response back to the client. In this case, I'd want the transaction to rollback but I didn't find a way of doing that.
Is it even possible to rollback the transaction in this case? Maybe there is a Spring platform limitation I'm overlooking.
Thanks
EDIT: To answer the replies below and specify the question further: It's easy enough to rollback the transaction. The tricky part is to run any code in response to the network failure. I was hoping that I can configure Spring to do it for me. Like "wait until you sent the last byte and then rollback or commit the transaction". My current code will commit the transaction as soon as the createEntity() method has finished.
Upvotes: 2
Views: 2224
Reputation: 2168
This is not Spring framework's limitation. Once the method is executed successfully, it is NOT spring framework's @Transactional
responsibility to roll it back.
The best you could do is to have an ExceptionHandler. See this answer for a better perspective: https://stackoverflow.com/a/45034574/945214
The other thing you could do is to improve the performance of the whole HTTP request topology, so that the probability of the such potential failure(s) reduces (as the touch time decreases). See my writeup on app performance at: https://www.linkedin.com/pulse/improving-website-performance-kshitiz-garg/
Upvotes: 1
Reputation: 2603
You can rollback Transaction without throwing an exception using:
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
Upvotes: 0
Reputation: 863
If you can find out when you need to rollback (checking a return status/...), you can just throw your own Exception.
Watchout as it only rollbacks for unchecked Exception (otherwise, you'll need to add rollbackFor=Exception.class
on your @Transactional
if you want it to rollback for any exception).
See :
https://www.catalysts.cc/wissenswertes/spring-transactional-rollback-on-checked-exceptions/
Annotation @Transactional. How to rollback?
Upvotes: 0