为什么Grails中的setter调用两次保存? [英] Why are setters in Grails called twice on save?

查看:85
本文介绍了为什么Grails中的setter调用两次保存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



<$ p

$ p $ class Idtest {

字符串名称

void setName(String name){
if(!this.id)
this.name = name +TEST
else
this.name = name
}

}

如果我使用 generate-all 生成视图和控制器,请启动该应用程序,然后输入hello 在生成的表单中,helloTESTTEST已保存。



save 函数如下所示:

  def save = {
def idtestInstance = new Idtest(params)
if(idtestInstance.save(flush:true )){
flash.message =$ {message(code:'default.created.message',args:[message(code:'idtest.label',default:'Idtest'),idtestInstance.id] )}
redirect(action:show,id:idtestInstance.id)
}
else {
render(view:create,model:[idtestInstance:idtestInstance])
}
}

为什么setter调用两次?

解决方案

b if(!this.id){}



您应该使用beforeInsert()

GORM高级功能


Look at the following Grails domain class, which modifies a value within a setter, if the object is saved the first time (if it has no id):

class Idtest {

  String name

  void setName(String name) {
    if(!this.id)
      this.name = name + "TEST"
    else
      this.name = name
  }

}

If I generate views and controller with generate-all, start the app, and enter "hello" in the generated form, "helloTESTTEST" is saved.

The save function looks like this:

def save = {
    def idtestInstance = new Idtest(params)
    if (idtestInstance.save(flush: true)) {
        flash.message = "${message(code: 'default.created.message', args: [message(code: 'idtest.label', default: 'Idtest'), idtestInstance.id])}"
        redirect(action: "show", id: idtestInstance.id)
    }
    else {
        render(view: "create", model: [idtestInstance: idtestInstance])
    }
}

Why is the setter called twice?

解决方案

Instead of doing if(!this.id){ }

You should use beforeInsert()

GORM Advanced Features

这篇关于为什么Grails中的setter调用两次保存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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