Using @Transactional disables grails default transaction management

According to grails docs, by default, transactions are transactional. But I know that you can get finer transaction control using the Transactional attribute.

If I have a service like

 class MyService { @Transactional(...config...) def method1() { } def method2() { } } 

I understand that in this case method1 will be transactional, but method2 will not.

If i have

 class MyService { def method1() { } def method2() { } } 

Then both method1 and method2 will be transactional.

Is it correct?

+6
source share
2 answers

If you want your service as transactional, set true for the transaction property (this is not necessary, but if you want to clearly indicate that the service is transactional):

 class MyService { static transactional = true def method1() { } def method2() { } } 

If you do not want:

 class MyService { static transactional = false @Transactional(...config...) def method1() { } def method2() { } } 

Another example (setting a transaction property is optional, but helps to be clear - if you're not the only encoding):

 import org.springframework.transaction.annotation.Transactional class BookService { @Transactional(readOnly = true) def listBooks() { Book.list() } @Transactional def updateBook() { // … } def deleteBook() { // … } } 

Another thing you can do is annotate the whole class and override the methods you need to be different:

 import org.springframework.transaction.annotation.Transactional @Transactional class BookService { @Transactional(readOnly = true) def listBooks() { Book.list() } def updateBook() { // … } def deleteBook() { // … } } 

Hope this helps;)

+6
source

You can disable Grails default transaction management by closing withTransaction for domains to manually manage the transaction as follows:

 Account.withTransaction { status -> try { //write your code or business logic here } catch (Exception e) { status.setRollbackOnly() } } 

If an exception is thrown, the transaction will be canceled.

+1
source

Source: https://habr.com/ru/post/924921/


All Articles