【问题标题】:grails - afterDelete() accessing domain propertiesgrails - afterDelete() 访问域属性
【发布时间】: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.propertiesHistory_Product 的第二个构造函数只包含 NULL 值。我不知道afterInsertafterUpdateafterDelete 方法之间的区别在哪里。我还尝试使用beforeDelete 方法以防删除但没有成功。

有什么猜测吗?

编辑:

我现在检查是否可以直接在afterUpdateafterDelete 中访问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


    【解决方案1】:

    我不得不请你原谅。我隐瞒了一些显然对解决问题至关重要的信息——我没想到它很重要。所以这就是我最终发现的:

    我的班级Product 与另一个名为ProductDetail 的班级存在一对多关系。因此,在Product 内我有static hasMany = [productDetails:ProductDetail]ProductDetail 域类看起来与此类似:

    @Entity
    class ProductDetail {
        Product product
    }
    

    我不记得为什么了,但很明显我忘了把static belongsTo=[product:Product] 代替上面写的Product product 行。

    最终,更改单行解决了我的问题,最后我可以访问Product 对象的properties

    顺便说一句,ProductDetail 对象是否存在无关紧要。如果belongsTo 丢失,则无法访问Product 端的properties 属性。

    【讨论】:

    • 我看不出这有什么关系,因为 belongsTo 属性只指定保存和删除应该传播到 ProductDetail。
    猜你喜欢
    • 2010-10-29
    • 2012-07-02
    • 1970-01-01
    • 2014-06-15
    • 1970-01-01
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多