grails回滚db操作时出现某些错误

| 我有一项将大量数据保存到db的服务。 使用MYSQL 我已经习惯了
Domain1.withTransaction {text->
            def domain1=//Create my domain object to save 
             if(!domain1.save()){
               domain1.errors.each {
                      println it
               }
               throw new RuntimeException(\'unable to save domain1\')
        }
        Domain2.withTransaction {text->
            def domain2=//Create my domain object to save 
             if(!domain2.save()){
               domain2.errors.each {
                      println it
               }
               throw new RuntimeException(\'unable to save domain2\')
        }
我的问题,如果在保存domain2时发生任何问题,我还需要回滚domain1保存。 我需要从数据库中删除domain1。     
已邀请:
代替使用程序化事务处理,服务工件允许自动事务处理。这通常会导致代码更干净,更可维护。 在save()强制抛出RuntimeException时,也可以使用failOnError:true。 下面的例子:
class SomeService {

    static transactional = false

    def serviceMethod() {
        def domain1=//Create my domain object to save
        def domain2=//Create my domain object to save
        domain1.save(failOnError:true)
        domain2.save(failOnError:true)
    }
}
更新 在阅读了对另一个主题的回复之后,我正在重新讨论这个主题。 Grails集成测试不会回滚 请确认您的方言已设置为InnoDB,因为MyISAM表不是可事务的。这是在您的
Config.groovy
中配置的
dataSource {
      dialect= org.hibernate.dialect.MySQLInnoDBDialect
      ...
}
    
尝试删除Domain2.withTransaction {text->部分。 您的第一个电话已经在交易中。 如果您在方括号内做进一步的工作,则应保留在同一事务中,并且如果在检查domain2之后引发异常,则应回滚domain1。     
Domain2.withTransaction
闭包放入
Domain1.withTransaction
闭包中,因此Domain2事务中的错误将回滚Domain1和Domain2事务 像这样
Domain1.withTransaction {
      //....
      Domain2.withTransaction {
           //....
      } 
} 
    
如果您只想在引发未处理的未经检查的异常时将其回滚的单个事务,则不要启动嵌套事务。必要的代码更改如下所示:
Domain1.withTransaction {text->
  def domain1=//Create my domain object to save 
  if (!domain1.save()) {
    domain1.errors.each {
      println it
    }
    throw new RuntimeException(\'unable to save domain1\')
  }

  def domain2=//Create my domain object to save 
    if (!domain2.save()) {
      domain2.errors.each {
        println it
      }
    throw new RuntimeException(\'unable to save domain2\')
  }
}
    

要回复问题请先登录注册