Grails: setting transient fields in the map constructor

北城以北 提交于 2019-11-29 12:25:51

The map constructor in GORM uses the data binding mechanism, and transient properties are not data-bindable by default. But you can override this using the bindable constraint

class Test {
    //...
    String foo
    static transients = ['foo']

    static constraints = {
        foo bindable:true
    }
}
Tomas Bartalos

I've also replied to your original question, that you don't need json conversion to achieve what you need. However, If you need json conversion badly, why don't you implement it in your getters/setters?

class Test {
    String propsAsJson

    static transients = ['props']

    public Map getProps() {
        return JSON.parse(propsAsJson)
    }

    public void setProps(Map props) {
        propsAsJson = props as JSON
    }
}

//So you can do
Test t = new Test(props : ["foo" : "bar"])
t.save()

In this way you encapsulate the conversion stuff, and in DB you have your properties as Json.

You can simplify your case by adding the JSON-conversion methods to your domain class, they should have nothing to do with GORMing:

class Test {
    String title

    void titleFromJSON( json ){ 
      title = json.toStringOfSomeKind()
    }

    def titleAsJSON(){ 
      new JSON( title )
    }

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