在引导程序中拉取域映射并将其修改为Grails

时间:2015-02-26 05:30:46

标签: hibernate grails hibernate-mapping grails-2.0 grails-domain-class

我目前正在使用Grails-2.2.4,我想修改我的域映射从bootstrap的行为,以将dateCreated字段更改为自定义日期。在尝试拉取域的映射以修改autotimestamp行为时,GrailsDomainBinder.getMapping返回null。我错过了什么,这是我的代码

grailsApplication.domainClasses.each { gdc ->
        def domClass = gdc.clazz
        def grailsSave = domClass.metaClass.pickMethod('save', [Map] as Class[])

        domClass.metaClass.save = { Map params ->

            def m = GrailsDomainBinder.getMapping(domClass.class)
            println("The mapping ===>>>$m") /* **this gives Null**   */
            m.autoTimestamp = false
            def colList = []
            domClass.declaredFields.each{
                if(!it.synthetic)
                    colList.add(it.name.toString())
            }
            if(colList.contains("dateCreated")) {
                println(domClass.metaClass.getProperty(delegate,"dateCreated"));
                domClass.metaClass.setProperty(delegate,"dateCreated",new Date("11/5/1990"))
                grailsSave.invoke(delegate, [params] as Object[])
            }

            //...
        }
    }

我收到错误

Cannot set property 'autoTimestamp' on null object

1 个答案:

答案 0 :(得分:3)

我发现我做错了什么,从domainClasses.clazz返回的域对象没有返回GrailsDomainClass,而是返回默认的java类对象,而不是它需要的东西。使用委托而不是domClass工作。 这是工作代码欢呼:) ..

grailsApplication.domainClasses.each { gdc ->
    def domClass = gdc.clazz
    def grailsSave = domClass.metaClass.pickMethod('save', [Map] as Class[])

    domClass.metaClass.save = { Map params ->

        def m = GrailsDomainBinder.getMapping(delegate.getDomainClass())
        println("The mapping ===>>>$m") 
        m.autoTimestamp = false
        def colList = []
        domClass.declaredFields.each{
            if(!it.synthetic)
                colList.add(it.name.toString())
        }
        if(colList.contains("dateCreated")) {
            println(domClass.metaClass.getProperty(delegate,"dateCreated"));
            domClass.metaClass.setProperty(delegate,"dateCreated",new Date("11/5/1990"))
            grailsSave.invoke(delegate, [params] as Object[])
        }

        //...
    }
}