1

我不确定我是否在这里遗漏了一些东西,但是否可以在不使用 withTransaction 方法的情况下在 Grails 中(在 src/groovy 的 groovy 类中)进行手动事务管理?

我的应用程序中没有任何域类,因为我正在调用另一个 Java Web 应用程序的服务层。

4

3 回答 3

2

服务方法默认是事务性的。这是在 grails 中获取事务行为的最简单方法:

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

如果您需要比这更细粒度的控制,您可以通过 hibernate 以编程方式启动和结束事务:

class CustomTransactions {
    def sessionFactory

    def doSomething() {
        def tx
        try {
            tx = sessionFactory.currentSession.beginTransaction()
            // transactional stuff here
        } finally {
            tx.commit()
        }
    }
}
于 2013-09-23T15:46:29.803 回答
2

在 Grails 应用程序中启动事务的唯一方法是这个答案中提到的那些。

我的应用程序中没有任何域类,因为我正在调用另一个 Java Web 应用程序的服务层。

这真的是一个单独的应用程序,还是您的 Grails 应用程序所依赖的 Java JAR?如果是前者,那么事务应该由执行持久性的应用程序管理。

于 2013-09-23T16:23:12.643 回答
2

上面的方法也是正确的。

你也可以使用@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

  }

}

于 2014-07-18T10:02:39.080 回答