Why are setters in Grails called twice on save?

孤者浪人 提交于 2019-12-10 11:27:31

问题


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?


回答1:


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

You should use beforeInsert()

GORM Advanced Features




回答2:


I believe it is called once when you create the object and it is saved

Then it would be called again when you retrieved the object from the database.

So..

On saving to to the database the property is set, lets assume a counter = counter + 1. so now one is saved to the database.

When you retrieve the object from the database, the domain object setter will be called again thereby incrementing the counter again counter++

This is all an assumption since the there is no controller code here for us to see how you are creating and or saving the objects so dont bash me if I am completely off



来源:https://stackoverflow.com/questions/4096817/why-are-setters-in-grails-called-twice-on-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!