【发布时间】:2014-12-22 12:52:43
【问题描述】:
假设我有以下域类及其对应的历史域类,以便自动保存对原始域对象所做的任何更改:
@Entity
class Product {
String productName
static constraints = {
productName maxSize: 250
}
def afterInsert() {
History_Product hist = new History_Product(this)
hist.insertType = 'I'
History_Product.withNewSession {
hist.save()
}
}
def afterUpdate() {
History_Product hist = new History_Product(this)
hist.insertType = 'U'
History_Product.withNewSession {
hist.save()
}
}
def afterDelete() {
History_Product hist = new History_Product(this)
hist.insertType = 'D'
History_Product.withNewSession {
hist.save()
}
}
}
@Entity
class History_Product {
String productName
Char insertType
static constraints = {
productName nullable: true, maxSize: 250
}
History_Product() {}
History_Product(Product p) {
this.properties = p.properties
}
}
因此,每次创建、更新或删除 Product 对象时,都会创建一个新的 History_Product 以保存旧值。这就像创建和更新的魅力。但是,如果我想删除产品,它不起作用,因为 p.properties 与 History_Product 的第二个构造函数只包含 NULL 值。我不知道afterInsert、afterUpdate 和afterDelete 方法之间的区别在哪里。我还尝试使用beforeDelete 方法以防删除但没有成功。
有什么猜测吗?
编辑:
我现在检查是否可以直接在afterUpdate 或afterDelete 中访问properties。所以我在这两种方法的每一种中都添加了println this.properties 作为第一行。有趣的是,这适用于afterUpdate,但不适用于afterDelete。可能是什么原因?在我的控制器中,我刚刚输入了productInstance.delete flush:true。
第二次编辑:
最有趣的是,在afterDelete 中,我可以检索到productName 的值。不管我是只使用productName 还是this.productName。因此,对象不是“空的”。反正我不知道为什么properties的映射是NULL。
第三次编辑:
在我实际删除 productInstance 之前,我现在在控制器 delete 操作中添加了 println productInstance.properties。有了这个,它就可以工作了。有人对此行为有某种解释吗?
【问题讨论】:
标签: grails properties grails-domain-class