extensa5620
extensa5620

Reputation: 699

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

Upvotes: 1

Views: 225

Answers (1)

Chetan
Chetan

Reputation: 1707

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.

P.S. - 'Create' class is not equal to 'generate'.

Upvotes: 5

Related Questions