Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I call save() on an instance of a domain object in Grails?

From what I've read, save() informs the persistence context that an instance should be saved or updated. However, I have methods in a service that change the property of a domain instance without calling save() and the change appears instantly in my database, no problem.

Is the save() method just a more secure way of knowing that a domain instance will be updated after making a change (and catching errors with the failOnError mapping)? Should it be used EVERY time I change a domain instance's properties or is that overdoing it?

like image 962
Weezle Avatar asked Feb 28 '12 22:02

Weezle


1 Answers

If you create a new instance of a domain class, then a .save() call will tell the underlying Hibernate layer to persist the new object to the database. Without the .save() it won't be persisted to the database.

If you retrieve an object via a .get(myId), then any changes will be automatically persisted to the database at the end of the underlying transaction because Hibernate sees the object as "dirty". The end of a transaction is at the end of a method call to a transactional service or end of a request for controllers. You can call .save() if you want in these instances, but it isn't necessary. It does provide easy access to flushing Hibernate via .save(flush:true) or the failOnError usage for validation.

like image 56
schmolly159 Avatar answered Nov 16 '22 00:11

schmolly159