Question

I'm not sure if I'm missing something here but is it possible to do manual transaction management in Grails (in groovy classes in src/groovy) without using the withTransaction method?

I don't have any domain classes in my app as I'm calling into the service layer of another Java web application.

Was it helpful?

Solution

Service methods are transactional by default. This is the easiest way to get transactional behavior in grails:

class SomethingService {
    def doSomething() {
        // transactional stuff here
    }
}

If you need finer grained control than this, you can start and end transactions programmatically through hibernate:

class CustomTransactions {
    def sessionFactory

    def doSomething() {
        def tx
        try {
            tx = sessionFactory.currentSession.beginTransaction()
            // transactional stuff here
        } finally {
            tx.commit()
        }
    }
}

OTHER TIPS

The only way to start transactions in a Grails app are those mentioned in this answer.

I don't have any domain classes in my app as I'm calling into the service layer of another Java web application.

Is this really a separate application or just a Java JAR that your Grails app depends on? If the former, then the transactions should be managed by the application doing the persistence.

Above method is also correct.

You can also use @Transactional(propagation=Propagation.REQUIRES_NEW)

class SomethingService{

  def callingMathod(){
   /**
    * Here the call for doSomething() will
    * have its own transaction
    * and will be committed as method execution is over
    */
    doSomething()
  }


  @Transactional(propagation=Propagation.REQUIRES_NEW)      
  def doSomething() {       

       // transactional stuff here

  }

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top