Search code examples
grailsgroovygrails-orm

how does save() work in Grails?


If I have the following method in my controller:

def save() {
  def userInstance = new User(params)
  if (userInstance.save(flush: true)) {
    def file = request.getFile("myFile")
    userInstance.fileName = file.getOriginalFileName()
  }
}

Even though I've called .save() prior to calling request.fileName = file.getOriginalFileName() the database does have a value for fileName column. I would assume that nothing would get saved after calling .save()?


Solution

  • Hibernate (the underlying library that handles the db interaction) does a dirty checking (checks if a field of the object has been changed since the last time it was read from the database) during a flush and grails will always do a flush at the end of each request.

    So you can understand that even if you change the fileName field after you save the object, this change is applied in the db when the request is over.

    You can read more on this, by searching for hibernate entity states (for example this) or for "Open Session in View" pattern (used by default by grails)