Grails域类beforeDelete无法作为事务处理 [英] Grails domain class beforeDelete is not working as transactional
问题描述
我有一个具有用户名,fullName等属性的用户域类,以及一个UserRole关联类.
I have an user domain class with attributes like username, fullName, ... etc. and a UserRole association class.
在我的域类中,在beforeDelete方法上有以下代码
In my domain class I have the following code on the beforeDelete method
def beforeDelete() {
UserRole.removeAll(this);
}
在UserRole类中,我具有如下的removeAll方法:
In the UserRole class I have the removeAll method like this:
static void removeAll(User user) {
executeUpdate 'DELETE FROM UserRole WHERE user=:user', [user: user]
}
对delete方法的调用在我的UserService类中完成
The call to the delete method is done in my UserService class
def delete(User userInstance){
userInstance.delete()
}
我期望的是:当删除失败时,应该执行回滚,但是即使删除失败,也会删除所有UserRole关联.
What I am expecting is: When deletion fails a rollback should be performed, but even when deletion fails all the UserRole associations are being deleted.
我错过了什么吗? 将beforeDelete方法与userService.delete(User userInstance)方法包装在同一事务中吗?
Am I missing something? The beforeDelete method is not wrapped in the same transaction as the userService.delete(User userInstance) method?
还是应该将UserRole.removeAll()调用移至UserService类?
Or should I move the UserRole.removeAll() call to the UserService class?
Grails版本:2.3.11
Grails Version: 2.3.11
休眠:3.6.10.16
Hibernate: 3.6.10.16
推荐答案
除了服务,没有配置的Grails都不是事务性的.没有@Transactional
批注且没有static transactional
属性的服务是事务性的.添加一个或@Transactional
批注使您可以自定义服务和/或方法的行为.使服务成为非事务性的唯一方法是删除所有注释并设置static transactional = false
. Grails应用程序中没有其他东西是事务性的.
Nothing in Grails is transactional without configuration except services. A service with no @Transactional
annotations and no static transactional
property is transactional. Adding one or @Transactional
annotations lets you customize the behavior for the service, and/or per-method. The only way to make a service non-transactional is to remove all annotations and set static transactional = false
. Nothing else in a Grails app is transactional.
您可以在控制器和域类withTransaction
方法中使用@Transactional
,但是两者都具有不足之处,应始终使用服务.
You can use @Transactional
in controllers and the domain class withTransaction
method, but both are hackish and services should always be used.
您可以在域类中使用依赖项注入,因此我将所有更新代码移至服务方法并从域类事件方法中调用它:
You can use dependency injection in domain classes, so I'd move all of the update code to a service method and call that from the domain class event method:
class MyDomain {
...
def myService
def beforeDelete() {
myService.beforeDeleteMyDomain this
}
}
或者,由于您已经在删除服务,因此您可以将所有内容组合为一种方法:
Or, since you're deleting in a service already, you can just combine everything in one method:
def delete(User userInstance){
UserRole.removeAll userInstance
userInstance.delete()
}
这篇关于Grails域类beforeDelete无法作为事务处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!