Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
742 views
in Technique[技术] by (71.8m points)

insert - Grails domain beforeInsert / beforeUpdate

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...