2016-07-29 39 views
0

Gibt es eine Möglichkeit der Herstellung Struktur folgt:Grails hasOne und hasMany mit derselben Domäne und Kaskadenbetrieb

class Parent { 
    String name 
    static hasOne = [firstChild: Child] 
    static hasMany = [otherChildren: Child] 
} 


class Child{ 
    String name 
    static belongsTo = [parent: Parent] 
} 

Jetzt, wenn ich versuche, einen einfachen Code auszuführen:

Parent p = new Parent(name: "parent", firstChild: new Child(name: 'child')) 
p.addToOtherChildren(new Child(name: "child2")); 
p.addToOtherChildren(new Child(name: "child3")); 
p.save(flush: true) 

Es das Objekt speichert aber wenn ich versuche, eine Liste Operation auf Eltern zu tun, wirft es diesen Fehler:

org.springframework.orm.hibernate4.HibernateSystemException: More than one row with the given identifier was found: 2, for class: test.Child; nested exception is org.hibernate.HibernateException: More than one row with the given identifier was found: 2, for class: test.Child 

Das Problem hier ist hasOne st Erteilt die Parent-ID in Child, genauso wie hasMany mit anglesTo, jetzt hat mehr als eine Child-Instanz dieselbe Eltern-ID, daher ist es schwierig zu entscheiden, welche für FirstChild ist.

Ich habe this solution versucht, so gut, aber es wirft diese Ausnahme:

org.springframework.dao.InvalidDataAccessApiUsageException: Not-null property references a transient value - transient instance must be saved before current operation : test.Child.parent -> test.Parent; nested exception is org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation : test.Child.parent -> test.Parent

Gibt es einen besseren Weg, es zu tun, oder mache ich etwas falsch?

Ich möchte FirstChild und andereChildren mit übergeordneten speichern.

Antwort

1

Laut Fehlermeldung (transient), müssen Sie saveparent vor dem Hinzufügen von Kindern:

Parent p = new Parent(name: "parent") 

if(p.save()){ 
    p.firstChild=new Child(name: 'child'); 
    p.addToOtherChildren(new Child(name: "child2")); 
    p.addToOtherChildren(new Child(name: "child3")); 
    p.save(flush: true) 
}