简体   繁体   English

Grails 数据绑定

[英]Grails data binding

I need to bind request parameters to an instance of the following Java class (getters and setters omitted):我需要将请求参数绑定到以下 Java class 的实例(省略了获取器和设置器):

public class ShippingHouse {

    private String name;
    private String description;
    private List<ShippingRule> shippingRules = new ArrayList<ShippingRule>();  
}

public class ShippingRule {

    private ShippingHouse shippingHouse;
    private String name
}

Notice that there is a 1:N relationship between ShippingHouse and ShippingRule , but each ShippingRule also has a reference to the ShippingHouse thaat owns it.请注意, ShippingHouseShippingRule之间存在 1:N 关系,但每个ShippingRule还具有对拥有它的ShippingHouse的引用。

If these were Grails command/domain classes, I would bind them with request parameters如果这些是 Grails 命令/域类,我会将它们与请求参数绑定

name=foo&description=bar&shippingRules[0].name=sr0&shippingRules[1].name=sr1

But it doesn't seem like this will set the reference to the owning ShippingHouse within each ShippingRule .但这似乎不会在每个ShippingRule中设置对拥有ShippingHouse的引用。 Is there a way I can bind this automatically, or must I write the code myself?有没有办法可以自动绑定它,或者我必须自己编写代码?

Don,大学教师,

You will need to write code to do it yourself using BindUsing or some other approach.您需要使用 BindUsing 或其他方法自己编写代码。 The binder doesn't (and shouldn't) assume anything about back references from a parent to a child.活页夹不(也不应该)假设任何关于从父母到孩子的反向引用。 If these were GORM entities and the relationship was explicit, that is different, but in your case the binder should not assume that shippingHouse property in the ShippingRule class has anything to do with the shippingRules property in the ShippingHouse class.如果这些是 GORM 实体并且关系是明确的,那就不同了,但在您的情况下,绑定程序不应假定 ShippingRule class 中的 shippingHouse 属性与 ShippingHouse class 中的 shippingRules 属性有任何关系。

Also note that lucke84 said that your "private" is implicit.另请注意,lucke84 表示您的“私人”是隐含的。 Make sure you understand what that means if you are going to remove them.如果要删除它们,请确保您了解这意味着什么。 If you remove them the compiler is going to generate public getter and setter methods for those properties, which may or may not be what you want.如果您删除它们,编译器将为这些属性生成公共 getter 和 setter 方法,这可能是您想要的,也可能不是。

If you want to implement a 1:N relationship between the two classes, you should use the right grails approach.如果要实现两个类之间的 1:N 关系,则应使用正确的 grails 方法。 Something like this:像这样的东西:

class ShippingHouse {
    String name
    String description
    static hasMany = [shippingRules: ShippingRule]
}

class ShippingRule {
    String name
    static belongsTo = [shippingHouse: ShippingHouse]
}

Please note that semicolons are useless and the "private" declaration on class fields is implicit.请注意,分号是无用的,并且 class 字段上的“私有”声明是隐含的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM