現在のプロジェクトでは、1 対多の関係を維持できません。関係の両側が保存されます - それらの間のリンクが失われるだけです。
私の 2 つのドメイン間の 1 対多の関係は次のようになります。
class Parent {
String name
...
static hasMany = [childs: Child]
Parent() {}
Parent(SomeOtherClass obj) {
this.properties = obj.properties
}
}
class Child {
int code
String description
}
Parent
内にインスタンスを作成していますParentService
:
public Boolean createParents(List parentIds) {
boolean savedSuccessfully = true
Parent.withTransaction {status ->
parentIds.each { parentIdString ->
if (parentIdString && parentIdString.isInteger()) {
int parentId = parentIdString.toInteger()
def parentInstance = new Parent(someOtherService.getExternalParentObj(parentId))
someOtherService.getExternalChilds(parentId).each { entry ->
parentInstance.addToChilds(Child.findOrSaveWhere(code: entry.key, description: entry.value))
}
if(!parentInstance.save()) {
status.setRollbackOnly()
savedSuccessfully = false
}
}
}
}
return savedSuccessfully
}
Parent
インスタンスとインスタンスの両方Child
が作成され、正常に保存されます。親と子の間のリンクだけが欠落しています。各インスタンスのchilds
プロパティはParent
空のリストです。
ここで何が悪いのかわかりません。関係が持続しないのはなぜですか?何か案は?
アップデート
すべてのインスタンスを作成した後にリストParentService
の存在をテストするための統合テストを追加しました:childs
Parent
...
assert parentService.createParents(["123","234","356"]) == true
def parent = Parent.get(1)
assert parent.childs.size() > 0
...
予想外に - テストに合格しました。