Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does using @Transactional disable the grails default transaction management

According to the grails docs, services are transactional by default. But, I know you can get more fine grained control of transactions by using the Transactional attribute.

If I have a service such as

class MyService {

    @Transactional(...config...)
    def method1() { }

    def method2() { }

}

My understanding is 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 both be transactional.

Is this correct?

like image 427
Jeff Storey Avatar asked Sep 08 '12 16:09

Jeff Storey


1 Answers

If you want your service as transactional set to true the transactional property (this isn't obligatory but if you want to make clear that the service is transactional):

class MyService {

    static transactional = true

    def method1() { }
    def method2() { }

}

If you don't want to:

class MyService {

    static transactional = false

    @Transactional(...config...)
    def method1() { }

    def method2() { }

}

Another example (setting transactional property isn't obligatory, but helps to be clear - if you are not the only coding this):

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 ;)

like image 179
Roberto Perez Alcolea Avatar answered Oct 13 '22 11:10

Roberto Perez Alcolea