tags:

views:

519

answers:

3

The Grails code below throws the following exception when trying to .save() the Foo object:

org.hibernate.TransientObjectException/
org.springframework.dao.InvalidDataAccessApiUsageException: 
object references an unsaved transient instance - 
save the transient instance before flushing: Bar

I guess I'm missing out on some of the GORM semantics in connection with automatically populating domain objects from HTTP params.

My question is simply:

  • What is the correct way to populate and save the Foo object, without getting said exception?

Model:

class Foo {
  Bar bar
}

View:

<g:form id="${foo.id}">
  <g:select name="foo.bar.id" from="${Bar.list()}" />
</g:form>

Controller:

class FooController {
  def fooAction = {
    Foo foo = new Foo(params)
    foo.save()
    [ foo: foo ]
  }
}
+1  A: 

If 'Bar' only exists in the context of Foo, add the following line to Bar.groovy

class Bar {
   static belongsTo = Foo

}

If 'Bar' is used in other context, you might use in Foo.groovy

class Foo {
  Bar bar
  static mapping = {
 bar cascade:'all-delete-orphan'
  }


}
Stefan
A: 

Hi, I had the same error and it turns out the problem was that I had overridden the id generation in the child class. The id generation should only be in the parent. This solved the error for me. Thanks

sarah
A: 

Please disregard above (it was a problem but not related to the error above)

sarah