Grails数据绑定怀疑

时间:2011-05-18 14:48:12

标签: data-binding grails

   Class Carro {
String name
String marca
String matricula

} 

Class CarroMovel{

String pro1
String prop2
String prop3

Carro carro

static hasMany = [ carros: Carro]

}

 def save2 = {

                def carroInstance = new Carro()
                def carroMovelInstance = new CarroMovel()

                carroInstance.name = params.name
                carroInstance.marca = params.marca
                carroInstance.matricula = params.matricula

                carroMovelInstance.prop1 = params.carroMovel.prop1
                carroMovelInstance.prop2 = params.carroMovel.prop2
                carroMovelInstance.prop3 = params.carroMovel.prop3

                carroInstance.save()
                carroMovelInstance.carro = carroInstance
                carroMovelInstance.save()                 

            }

CarroInstance正在保存,但carroMovelInstance不是。我想不明白。任何帮助都会被贬低。

2 个答案:

答案 0 :(得分:1)

你永远不会要求carroMovelInstance保存... carro实例也没有引用carroMovel实例所以没有级联保存

答案 1 :(得分:1)

Grooveek is correct您尚未调用carroMovelInstance.save()

但是,您可以更简单地利用Grails的数据绑定,而不是不必要地创建关联并手动绑定参数。

// Update your Carro domain.
def Carro {
    String name
    String marca
    String matricula

    // will cause persistence operations to cascade from CarroMovel to Carro
    static belongsTo = CarroMovel
}

// Update your save2 action.
// By passing 'params' to the CarroMovel constructor, Grails will bind request
// parameters to domain properties of the same name; it even works with associations!
def save2 = {
    def carroMovelInstance = new CarroMovel(params)
    if(carroMovelInstance.validate) {
        carroMovelInstance.save()
    }
}

阅读Grails Data Binding,特别是有关关联的部分。另外,请阅读"Understanding Cascading Updates and Deletes"以了解对父域对象的save()的调用将如何(或不会)级联到关联的域对象。