Search code examples
grailscollectionsgrails-ormgetter-settertransient

Grails domain class transient collection attribute setter issue


I am trying to set (or bind) value to a transient List attribute. But I failed with collections. On the other hand transient String attribute working well on setter.

Grails version 2.4.3

Any advice?

@Resource(uri = "/api/samples", formats = ["json"])
class Sample {

    static transients = ["fields","sample"]

    String regions
    String name
    String sample


    List<String> fields

    List<String> getFields() {
        this.regions != null ? Arrays.asList(regions.split("\\s*,\\s*")) : new ArrayList<String>();
    }

    void setFields(List<String> fields) {
        if (fields != null && !fields.isEmpty()) {
            this.regions = fields.join(",")
        }
    }

    void setSample(String sample){
        this.name = sample
    }

    static mapping = {
    }
}

Solution

  • Untyped fields are transient by default, so this alternative approach should work (and is a lot more concise):

    @Resource(uri = "/api/samples", formats = ["json"])
    class Sample {
    
        static transients = ["sample"]
    
        String regions
        String name
        String sample
    
    
        def getFields() {
            this.regions != null ? Arrays.asList(regions.split("\\s*,\\s*")) : []
        }
    
        void setFields(def fieldList) {
            if (fieldList) {
                this.regions = fieldList.join(",")
            }
        }
    
        void setSample(String sample){
            this.name = sample
        }
    
        static mapping = {
        }
    }