Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transaction rollback in Spring MVC controller

I have a Spring MVC controller annotated with @Transaction, and under certain inputs I need to rollback the transaction.

As I understand, the proper way to trigger a rollback is to throw an exception from the controller.

But if I throw an exception from the controller, I won't get a chance to return a ModelAndView object from the controller.

How can I trigger a rollback in the controller, while still providing a ModelAndView to be rendered?

like image 498
Will Avatar asked Apr 17 '26 09:04

Will


2 Answers

Exceptions are the appropriate route to follow. Spring can map exceptions to views as well. This is probably what you want to do.

like image 70
Ryan Stewart Avatar answered Apr 18 '26 23:04

Ryan Stewart


First, I don't think that using @Transaction on controller methods is a good thing. It's better to keep transactional logic in a 'service tier' and use the @Transaction annotation there.

But if you still want to use @Transaction on the controller, take a look at org.springframework.web.servlet.handler.SimpleMappingExceptionResolver

like image 43
robi Avatar answered Apr 18 '26 22:04

robi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!