具有一对多关系的 Grails 数据绑定 - 返回父级的链接丢失



在Grails 2.2.2应用程序中,我有一个一对多的关系,看起来像这样:

父母:

class Client {
    ...
    String name
    static hasMany = [modelFieldInstances: ModelFieldInstance]
    ...
}

孩子:

class ModelFieldInstance {
    ...
    String name
    String value
    static belongsTo = [client: Client]
    ...
}

我正在尝试创建一个数据导入器,以便用户可以导入包含其客户记录的电子表格或 csv。为此,我检查了 grails 脚手架在标准脚手架控制器的save方法中创建新的Client实例时使用的参数。

问题是,当我尝试使用导入器创建和保存新的Client实例时,子ModelFieldInstance被保存而不引用父Client(ClientModelFieldInstance都保留了(。

在我的导入器中,我像这样执行数据绑定:

Client client = new Client()
client.modelFieldInstances = ListUtils.lazyList(new ArrayList(), {new ModelFieldInstance()} as org.apache.commons.collections.Factory)
client.properties = properties
...
client.save()

我认为 Grails 脚手架控制器的工作方式与我的导入器的工作方式之间唯一真正的区别是,在我的导入器中,我最初将modelFieldInstances集合设置为LazyList。但是,在我添加LazyList赋值之前,数据绑定因出现如下错误而失败:

Invalid property 'modelFieldInstances[31]' of bean class [com.myapp.Client]: Illegal attempt to get property 'modelFieldInstances' threw exception; nested exception is org.springframework.beans.InvalidPropertyException: Invalid property 'modelFieldInstances[31]' of bean class [com.myapp.Client]: Cannot get element with index 31 from Set of size 0, accessed using property path 'modelFieldInstances[31]'**

所以,我想问题是,当我可以看到数据绑定在给定属性映射的基架控制器中确实有效时,为什么数据绑定在我的数据导入器中不起作用。

作为一种解决方法,我实现了一种方法,该方法遍历modelFieldInstances集合中的所有项,并手动将父项(client(分配给每个项。这似乎工作正常,但是我仍然不确定为什么 grails 数据绑定不为我执行此操作。我想知道GrailsParameterMap是否发生了一些魔法......

最新更新