开发者

Grails GORM problem: Object references an unsaved transient instance

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()开发者_StackOverflow
    [ foo: foo ]
  }
}


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'
  }


}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜