Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grails - tell me if anything is dirty?

Grails provides an isDirty method that can be called on domain objects. How would one modify the Grails domain model system, such that one could simply call a method, to find out if any domain objects are dirty.

I'm struggling with some "unsaved transient instance" errors that I haven't been able to nail down, and it'd be great to know what's dirty. Is there an elegant way to do this with groovy?

like image 626
Ray Avatar asked Jan 01 '12 03:01

Ray


2 Answers

Add this to BootStrap.groovy:

import org.hibernate.Session

Session.metaClass.isDirty = { ->
   delegate.persistenceContext.entitiesByKey.values().any { it.isDirty() }
}

This adds an isDirty() method to Hibernate sessions that checks that top-level instances or instances in collections are dirty and you can use it with withSession, e.g.

boolean dirty = SomeDomainClass.withSession { session -> session.isDirty() }

or if you have access to the sessionFactory bean (e.g. from a def sessionFactory dependency injection)

boolean dirty = sessionFactory.currentSession.isDirty()
like image 119
Burt Beckwith Avatar answered Nov 14 '22 23:11

Burt Beckwith


Based on Burt's answer, one might also do:

   Session.metaClass.whatsDirty = { ->
       def everythingDirty = []
       delegate.persistenceContext.entitiesByKey.values().each { if (it.isDirty()) everythingDirty.add(it) }
       return everythingDirty
    }
like image 3
Ray Avatar answered Nov 14 '22 22:11

Ray