1

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.

Dónal
  • 185,044
  • 174
  • 569
  • 824
dre
  • 1,027
  • 1
  • 11
  • 31

3 Answers3

2

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()
        }
    }
}
ataylor
  • 64,891
  • 24
  • 161
  • 189
  • 1
    You can also use the Spring `@Transactional` annotations on service methods – Dónal Sep 23 '13 at 16:20
  • If the app has no domain classes there would be no reason to have the hibernate plugin installed, so the above wouldn't even be possible – Dónal Sep 24 '13 at 13:13
2

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.

Community
  • 1
  • 1
Dónal
  • 185,044
  • 174
  • 569
  • 824
2

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

  }

}

VMAtm
  • 27,943
  • 17
  • 79
  • 125