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?
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()
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With