GORM goodies read, discard, refresh

07 / Sep / 2010 by Uday Pratap Singh 0 comments

Grails docs are the best source to understand how to make best use of GORM methods and now the GORM Gotcha’s series By Peter Ledbrook is also making the docs easy to understand.
So many time it happens when the domain instance values gets updated without calling save method.It happens because the object is attached to hibernate session, to change this behavior we can use the method like read instead of get/load.
What read actually do is

Person person = Person.read(1)
println "Output -: ${person?.firstname}"  // Output -: Uday
person.firstname="Uday1"
println "Output -: ${person?.firstname}" // Output -: Uday1

The value is changed but it is not stored in the database. But the changes can be saved into the database if you explicitly call save().

The other approach could be removing the object from hibernate session, so that the changes made to the database do not get persisted to the database

Person person = Person.get(1)
println "Output -: ${person?.firstname}"  // Output -: Uday
person.firstname = "Uday1"
println "Output -: ${person?.firstname}" // Output -: Uday1
person.discard()
println "Output -: ${person?.firstname}"  // Output -: Uday1

In above example, any change made to the object do not get persisted to the database . Again it will save the changes if you explicitly call save().

One more good method is refresh() which is used to load the object again from the database, so all the changes made to object will be reverted. Though it is not advisable but sometimes if you want to get the object to its original stage you can do it by refresh.

Person person = Person.get(1)
println "Output -: ${person?.firstname}" // Output -: Uday
person.firstname = "Uday1"
println "Output -: ${person?.firstname}" // Output -: Uday1
person.refresh()
println "Output -: ${person?.firstname}" // Output -: Uday

These are the few goodies which are available with the GORM and we can use according to our use case :).

Hope it helps
Uday Pratap Singh
uday@intelligrape.com

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *