Grails Domain beforeInsert / beforeUpdate

I want to save my domain class in the database without specifying createdUseror createdDate. Ive created an object with the name AuditingInfoand entered it in the main class of the domain Personas follows:

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 can not use events beforeInsertand beforeUpdatein the classroom Person, or AuditingInfobecause he always brings NullPointerExceptionin org.grails.datastore.mapping.engine.event.AbstractPersistenceEventListener. Therefore, I want to use the method metaClassas shown below (this action is defined in the file *GrailsPlugin.groovy, 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 very much.

+2
source share
2 answers

metaClass Bootstrap.groovy, .

+3

doelleri

:

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

BootStrap.groovy

+2

All Articles