Jeff Storey
Jeff Storey

Reputation: 57212

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?

Upvotes: 6

Views: 4046

Answers (2)

Piyush Chaudhari
Piyush Chaudhari

Reputation: 1012

You can disable the Grails default transaction management using withTransaction closure for domains to manage your Transaction manually as follows:

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

If an exception is thrown, then the Transaction will be rollbacked.

Upvotes: 1

Roberto Perez Alcolea
Roberto Perez Alcolea

Reputation: 1414

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

Upvotes: 6

Related Questions