【问题标题】:Grails manual transactions with no domain classes没有域类的 Grails 手动事务
【发布时间】:2013-09-23 15:21:13
【问题描述】:

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

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

【问题讨论】:

    标签: grails transactions service-layer


    【解决方案1】:

    服务方法默认是事务性的。这是在 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()
            }
        }
    }
    

    【讨论】:

    • 你也可以在服务方法上使用Spring @Transactional注解
    • 如果应用没有域类,就没有理由安装hibernate插件,所以上面甚至不可能
    【解决方案2】:

    在 Grails 应用程序中启动事务的唯一方法是 this answer 中提到的那些。

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

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

    【讨论】:

      【解决方案3】:

      上面的方法也是正确的。

      你也可以使用@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-10-06
        • 1970-01-01
        • 2014-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多