GORM dirty checking of instance and properties

16 / Sep / 2010 by Uday Pratap Singh 4 comments

Again I am going to showcase few useful methods that GORM provides us to check whether the object is dirty or not (again from grails.org).
First question could be what is a dirty object? An object is dirty if the current state of its properties does not match with its persistence values. It happens when you modify few properties of an object e.g.:

Person person = Person.get(1)
println "Output -: " + person.firstname //Output -: Uday  
person.firstname = "Test"
println "Output -: ${person.firstname}" //Output -: Test
println "Output -: ${person.isDirty()}" //Output -: True
println "Output -: ${person.isDirty('lastname')}" //Output -: False 
println "Output -: ${person.isDirty('firstname')}" //Output -: True 

There is one more good method to retrieve which properties of the object are dirty.

println "Output -: ${person.dirtyPropertyNames}" //Output -: ['firstname']

Now, how can you get the actual value of that object? The actual value is modified and you want to get the persisted value. One “not so good” idea is to call refresh() which will load the object from the database again which might be a huge data retrieval in few cases. To solve this problem, GORM has given a simple method which will do the work for you:

println "Output -: ${ person.getPersistentValue('firstname')}" //Output -:Uday

A simple word in which I can define Grails is, it just “ROCKS”.

Hope it helps
Uday Pratap Singh
uday@intelligrape.com

FOUND THIS USEFUL? SHARE IT

comments (4)

  1. Chad Small

    Thanks for the post Uday/IntelliGrape. One other tidbit to watch out for, that I ran into, is if… you are check isDirty() status from a controller action and that prior to the isDirty() checking a transaction service is called for some reason, the hibernate session will be flushed and you will loose your isDirty() functionality.

    @chadsmall

    Reply
  2. Uday

    As per my understanding, the isDirty in hibernate checks whether the value is different from its persistent value of object or not, except for Collections, which are compared by identity.

    Reply
  3. kuba

    Thank you for sharing this information. I never used this GORM function so far.
    A guess: Is isDirty() also false if you attach a new String with person.firstname = “Uday”? Same content but different string?

    Reply

Leave a Reply

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