Grails 域 class beforeDelete 未作为事务处理

Grails domain class beforeDelete is not working as transactional

我有一个用户域 class,具有用户名、全名等属性和一个 UserRole 关联 class。

在我的域中 class 我在 beforeDelete 方法中有以下代码

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

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

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

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

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

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

我错过了什么吗? beforeDelete 方法未包装在与 userService.delete(User userInstance) 方法相同的事务中?

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

Grails 版本:2.3.11

休眠:3.6.10.16

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

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

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

class MyDomain {

   ...

   def myService

   def beforeDelete() {
      myService.beforeDeleteMyDomain this
   }
}

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

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