【问题标题】:Grails domain class beforeDelete is not working as transactionalGrails 域类 beforeDelete 不能作为事务性工作
【发布时间】:2015-03-04 01:31:04
【问题描述】:

我有一个用户域类,其中包含用户名、全名、...等属性和一个 UserRole 关联类。

在我的域类中,我在 beforeDelete 方法上有以下代码

def beforeDelete() {
    UserRole.removeAll(this);
}

在 UserRole 类中,我有这样的 removeAll 方法:

static void removeAll(User user) {
    executeUpdate 'DELETE FROM UserRole WHERE user=:user', [user: user]
}

删除方法的调用是在我的 UserService 类中完成的

def delete(User userInstance){
   userInstance.delete()
}

我的期望是:当删除失败时,应该执行回滚,但即使删除失败,所有 UserRole 关联也会被删除。

我错过了什么吗? beforeDelete 方法没有和 userService.delete(User userInstance) 方法封装在同一个事务中?

或者我应该将 UserRole.removeAll() 调用移至 UserService 类吗?

Grails 版本:2.3.11

休眠:3.6.10.16

【问题讨论】:

  • 尝试将调用移动到服务(removeAll)并调用它,看看是否有帮助

标签: grails grails-orm


【解决方案1】:

Grails 中除了服务之外,没有任何配置是事务性的。没有@Transactional 注释和static transactional 属性的服务是事务性的。添加一个或@Transactional 注释可让您自定义服务的行为和/或每个方法。使服务非事务性的唯一方法是删除所有注释并设置static transactional = false。 Grails 应用程序中的其他任何内容都不是事务性的。

您可以在控制器中使用 @Transactional 和域类 withTransaction 方法,但两者都是 hackish,应始终使用服务。

您可以在域类中使用依赖注入,因此我会将所有更新代码移动到服务方法并从域类事件方法中调用它:

class MyDomain {

   ...

   def myService

   def beforeDelete() {
      myService.beforeDeleteMyDomain this
   }
}

或者,由于您已经在服务中删除,您可以将所有内容组合在一种方法中:

def delete(User userInstance){
   UserRole.removeAll userInstance
   userInstance.delete()
}

【讨论】:

    猜你喜欢
    • 2013-03-08
    • 1970-01-01
    • 2011-01-31
    • 2014-10-06
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    相关资源
    最近更新 更多