简体   繁体   中英

Grails - @Transactional annotation on generating simple Controller

Grails newb here. I was using GGTS to generate a controller for a simple User model (string user, string passed)

On looking at the GGTS generated code, I noticed that there is @Transactional annotation on certain actions like delete(), save() and update().

My question is, why is @Transactional used in the controller and why is @Transactional not used in Services?

Newb in grails

In grails the correct way to do all DB related work and DB transactions is to do in service classes and not controllers. So by default controllers don't have privileges to do transaction and hence we use @Transactional annotation. While in services by default transaction is allowed.

If you use a service method which does some DB transaction then you need to make your controller action transactional by @Transactional annotation. While no need to mention it in service method.

Other way round if you donot make the controller transactional then you will need to mention it in service class.

Best practice will be not to use auto generated code as it will be less maintainable for a beginner. Official documentation will be your best help and while doing it when you will create controller you will not find any transactional annotation while when you will create service class you will see transactional annotation at the class level.

PS - 'Create' class is not equal to 'generate'.

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