Grails域beforeInsert / beforeUpdate

时间:2012-02-14 16:19:00

标签: grails insert grails-domain-class

我想将我的域类保存到数据库,而不指定createdUsercreatedDate。我创建了一个名为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
}

Person.groovy

class Person {
    static embedded = ['auditingInfo']
    AuditingInfo auditingInfo

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

我无法使用beforeInsert域或beforeUpdate类中的PersonAuditingInfo个事件,因为它始终会导致NullPointerException org.grails.datastore.mapping.engine.event.AbstractPersistenceEventListener }。 因此,我想使用metaClass方式,如下所示(此操作在*GrailsPlugin.groovy文件中定义,但不幸的是我的项目是Grails项目,而不是Grails插件项目):

def doWithDynamicMethods = { ctx ->       
    application.domainClasses.each { org.codehaus.groovy.grails.commons.GrailsDomainClass gc ->
        gc.metaClass.beforeInsert = {
        }

        gc.metaClass.beforeUpdate = {
        }
    }
}

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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

同意doelleri

只需添加您的代码:

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

进入BootStrap.groovy