Sunday, June 17, 2018

Grails on Groovy > Transactions > Transaction Block > Read Only Transactions > With New Transaction > Transactions With Read Only Stage

We all know that Grails services are transactional by default. When you create a service you see that there is a annotation @Transactional exists over class name. Transactional means all transactions will persist on database or no one will persist.
We can set transactions read only mode if we wish in a transactional block if we need. Below is a code snippet:
package com.pkm

import grails.transaction.Transactional
import org.springframework.transaction.TransactionStatus

@Transactional
class HomeService {
    TransactionStatus transactionStatus

    void callMe() {
        Table1 table1 = Table1.last()
        new Table2(table1: table1, subject: "S3", score: 3D).save()
        transactionStatus.setRollbackOnly()

        Table2.withNewTransaction { TransactionStatus tx ->
            table1 = Table1.last()
            new Table2(table1: table1, subject: "S4", score: 3D).save()
            tx.setRollbackOnly()
        }
    }
}
In above code block, we inject a bean named transactionStatus which actually maintain if a service definition is read only or not. We can set it to read only mode using transactionStatus.setRollbackOnly(). We can do the same job for when we do anything in withNewTransaction block. You can see there is another transactionStatus occur for that new region. So you can also set it to read only mode.

No comments:

Post a Comment