简体   繁体   中英

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?

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

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.

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