Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are controllers in Grails transactional by default?

Are controller actions in grails transactional by default? If not whats the best way to revert the changes at a certain point during execution of code in controllers.

like image 455
Ankit Agrawal Avatar asked Feb 03 '17 03:02

Ankit Agrawal


1 Answers

Almost nothing in Grails is transactional by default, with the exception of services in all but the more recent 3.1.x versions. In older versions if there was nothing configured for transactional behavior, all public methods would be transactional because a transactional proxy would be applied. You could disable that with static transactional = false or customize the transactional behavior with @Transactional annotations. You can (and should) still use @Transactional annotations in services - you just don't need to disable auto-transactionality.

Generated controllers and services do include @Transactional annotations, but that's just a shortcut to save you the work of adding them yourself.

Controllers are a bad place to do transactional work though, since you end up with lots of jumbled code in the controllers, but it's important to separate concerns and put code where it belongs (e.g. view generation in GSPs, domain properties and constraints in domain classes, transactional database writes and business logic in services, etc.) instead of simply dumping code where it's convenient.

Your best bet is to leave the request parameter data binding and routing logic in the controllers but move persistence and business logic to services that are explicitly configured to be transactional or not depending on what's needed per-class and per-method, and have the controllers call services and other helpers.

In addition to making the code more maintainable (by your coworkers and future you) this approach also makes it easier to properly test everything because your methods and classes are simpler and more focused.

like image 154
Burt Beckwith Avatar answered Nov 05 '22 00:11

Burt Beckwith