tags:

views:

26

answers:

0

I have an object foo, foo has a collection bars and each bar has a collection of baz

class foo {
 static hasMany = [
  bars : Bar
 ] 
}

class bar { 
 static belongsTo = [
  foo : Foo
 ]

 static hasMany = [
  bazs : Baz
 ]
}


class baz {
 static belongsTo = [
  bar : Bar
 ]
}

I was trying to create and save the foo structure this way

def bazsList = [new Baz()]
def foo = new Foo()
["test1","test2"].each { label ->
 def bar = new Bar(label:label)
 bazsList.each {
  bar.addToBazs(it)
 }  
 foo.addToBars(bar)
}
foo.save()

The code above creates an instance of Foo, builds a list of bar object from a list (["test1","test2"]) and each Bar object is associated to a list of bazsList. However the code throws a DataIntegrityViolationExcetpion: not-null property references a null or transient value Baz.bar. And i managed to solve the problem by cloning the baz objects before adding them to the list of Bazs for the bar object

def bazsList = [new Baz()]
def foo = new Foo()
["test1","test2"].each { label ->
 def bar = new Bar(label:label)
 bazsList.each {
  bar.addToBazs(BeanUtils.cloneBean(it))
 }  
 foo.addToBars(bar)
}
foo.save()

I don't really know why this is happening though. I understand that it's wrong to try to add the same baz object to bar but still that doesn't explain why Gorm is behaving this way or not just just linking all the bar object to the same instance of baz .

Thank you - ken