Grails: setting transient fields in the map constructor

后端 未结 3 1087
夕颜
夕颜 2020-12-20 03:27

I\'m trying to persist Maps of properties as single JSON-encoded columns, as shown in this question.

The problem I\'m having is that apparently transient pro

相关标签:
3条回答
  • 2020-12-20 03:49

    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.

    0 讨论(0)
  • 2020-12-20 03:50

    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 )
        }
    
    }
    
    0 讨论(0)
  • 2020-12-20 03:56

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题