Grails:在地图构造函数中设置瞬态字段 [英] Grails: setting transient fields in the map constructor

查看:346
本文介绍了Grails:在地图构造函数中设置瞬态字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将属性的地图作为单一JSON编码列,如这个问题

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

我遇到的问题是,显然 transient属性不能设置默认地图构造函数。给定任何暂时字段:

The problem I'm having is that apparently transient properties cannot be set in the default map constructor. Given any transient field:

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

看起来map构造函数Grails以各种方式覆盖)简单地丢弃了暂时字段:

It seems that the map constructor (which Grails overrides in various ways) simply discards transient fields:

groovy:000> t = new Test(foo:'bar')
===> Test : (unsaved)
groovy:000> t.foo
===> null

直接赋值(通过setter方法)按预期工作:

While direct assignment (through the setter method) works as expected:

groovy:000> c.foo = 'bar'
===> bar
groovy:000> c.foo
===> bar

有一种方法让地图构造函数接受临时字段吗?

Is there a way to make the map constructor accept transient fields?

或者说,有一个更好的方法来将 Map 数据库字段,而不是链接问题中显示的方法

Or rather: is there a better way to persist a Map as a single JSON-encoded DB field, rather than the method shown in the linked question?

下面是完整的示例:

import grails.converters.JSON

class JsonMap {
    Map data
    String dataAsJSON

    static transients = ['data']
    def afterLoad()      { data = JSON.parse(dataAsJSON) }
    def beforeValidate() { dataAsJSON = data as JSON }
}

我可以使用setter设置 data (然后将它转换为 dataAsJSON

I can set data using the setter (which will then be converted into dataAsJSON) but not using the map constructor.

推荐答案

GORM中的地图构造函数使用数据绑定机制,默认情况下不可数据绑定。但您可以使用可绑定的约束替换此操作

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
    }
}

这篇关于Grails:在地图构造函数中设置瞬态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆