I am constantly doing things wrong and getting unsaved transient instance exceptions in Grails. I cannot paste the code, and if I did you would probably just tell me to stop programming for ever. But here is the generic situation I would like some help with:
I call instanceOfMyComplicatedDomainClass.save(flush: true, failOnError: true)
and grails/hibernate gives me the ubiquitous:
object references an unsaved transient instance - save the transient instance before flushing: soexample.SomeOtherDomainClass
What can I do (other than understanding my own code) to see which property is the problem given I have several with the same class? I want a method I can call just before the .save()
which will println
/log
/whatever the name of the property that's causing all the huff. Let me make an example:
class MyComplicatedDomainClass {
SomeOtherDomainClass dataContents
SomeOtherDomainClass moreDataContents
static constraints = {
dataContents(nullable:true)
moreDataContents(nullable:true)
}
}
class SomeOtherDomainClass {
String randomData
}
...
def someRandomMethodAnywhere(){
def newComplicated = new MyComplicatedDomainClass()
def imUnsaved = new SomeOtherDomainClass(randomData:'lalala')
def imOK = new SomeOtherDomainClass(randomData:'lalala2').save()
newComplicated.dataContents = imUnsaved
newComplicated.moreDataContents = imOK
//At this point newComplicated references an unsaved transient, "imUnsaved". If I try to save newComplicated it will fail.
def badPropertyList = findUnsavedTransients(newComplicated)
assert badPropertyList.contains("dataContents") //So findUnsavedTransients method returns a list of the names of the properties referencing the unsaved transients
}
How would I go about writing the findUnsavedTransients? Is there any method already in Hibernate that will do a similar thing?
I am asking something different from my other question to list ALL unsaved transients everywhere: Get a list of all objects grails is planning to magically save
Also, I see (and have read) the ~15 other "Hibernate: unsaved transient..." questions, and I am asking for a generic solution to see what the problem is, rather than a specific solution to what I am doing wrong in today's particular snippet. Teach a man to fish... so to speak.