Grails domain beforeInsert / beforeUpdate

不想你离开。 提交于 2019-11-28 06:01:35

问题


I want to save my domain class to the database without specifying the createdUser or createdDate. I’ve created an object called AuditingInfo and embedded it in the main Person domain class like this:

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
}

I cannot use the beforeInsert and beforeUpdate events in the Person domain or AuditingInfo class, because it always causes a NullPointerException in org.grails.datastore.mapping.engine.event.AbstractPersistenceEventListener. Therefore, I want to use the metaClass way, as used below (this action is defined in a *GrailsPlugin.groovy file, but unfortunately my project is a Grails project, not a Grails plugin project):

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

        gc.metaClass.beforeUpdate = {
        }
    }
}

How can I apply this method to my project context? Thank you so much.


回答1:


You can apply your metaClass modifications from within your Bootstrap.groovy, which is executed at start-up.




回答2:


agree with doelleri

just add your code :

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

Into BootStrap.groovy



来源:https://stackoverflow.com/questions/9280340/grails-domain-beforeinsert-beforeupdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!