Grails域beforeInsert/beforeUpdate

Grails域beforeInsert/beforeUpdate,grails,insert,grails-domain-class,Grails,Insert,Grails Domain Class,我想在不指定createdUser或createdDate的情况下将域类保存到数据库中。我创建了一个名为AuditingInfo的对象,并将其嵌入主Person域类中,如下所示: AuditingInfo.groovy: class AuditingInfo { static constraints = { createdUser (nullable : true) updatedUser (nullable : true) created

我想在不指定
createdUser
createdDate
的情况下将域类保存到数据库中。我创建了一个名为
AuditingInfo
的对象,并将其嵌入主
Person
域类中,如下所示:

AuditingInfo.groovy

class AuditingInfo {
    static constraints = {
        createdUser (nullable : true)
        updatedUser (nullable : true)
        createdDate(nullable : true)
        updatedDate(nullable : true)
    }

    static mapping = {
        columns {
            createdUsercolumn: 'T_CREATED_USER'
            updatedUsercolumn: 'T_UPDATED_USER'
            createdDatecolumn: 'T_CREATED_DATE'
            updatedDatecolumn: 'T_UPDATED_USER'
        }
    }

    User createdUser
    User updatedUser
    Date createdDate
    Date updatedDate
}
class Person {
    static embedded = ['auditingInfo']
    AuditingInfo auditingInfo

    static constraints = { auditingInfo(nullable: true) }
    String name
    Long id
}
Person.groovy

class AuditingInfo {
    static constraints = {
        createdUser (nullable : true)
        updatedUser (nullable : true)
        createdDate(nullable : true)
        updatedDate(nullable : true)
    }

    static mapping = {
        columns {
            createdUsercolumn: 'T_CREATED_USER'
            updatedUsercolumn: 'T_UPDATED_USER'
            createdDatecolumn: 'T_CREATED_DATE'
            updatedDatecolumn: 'T_UPDATED_USER'
        }
    }

    User createdUser
    User updatedUser
    Date createdDate
    Date updatedDate
}
class Person {
    static embedded = ['auditingInfo']
    AuditingInfo auditingInfo

    static constraints = { auditingInfo(nullable: true) }
    String name
    Long id
}
我不能在
Person
域或
AuditingInfo
类中使用
beforeInsert
beforeUpdate
事件,因为它总是在
org.grails.datastore.mapping.engine.event.AbstractPersistenceEventListener
中导致
NullPointerException
。 因此,我希望使用下面使用的
元类
方式(此操作在
*GrailsPlugin.groovy
文件中定义,但不幸的是,我的项目是Grails项目,而不是Grails插件项目):


如何将此方法应用于我的项目上下文?非常感谢。

您可以在启动时执行的Bootstrap.groovy中应用元类修改。

同意doelleri的观点

只需添加您的代码:

application.domainClasses.each { org.codehaus.groovy.grails.commons.GrailsDomainClass gc ->
                    gc.metaClass.beforeInsert = {
                    }
                    gc.metaClass.beforeUpdate = {
                    }
        }
进入BootStrap.groovy