2

現在のプロジェクトでは、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の存在をテストするための統合テストを追加しました:childsParent

...
assert parentService.createParents(["123","234","356"]) == true
def parent = Parent.get(1)
assert parent.childs.size() > 0
...

予想外に - テストに合格しました。

4

1 に答える 1

0

エラーの原因がわかりました。

entry.valueいくつかあることを完全に見逃しましたnull。デバッグ中に表示されなかった理由がわかりません。

今はChild.findOrSaveWhere()if entry.valueis notのみを使用しますnull

parentInstance.save()全体が完全に合格または不合格になると予想していたでしょう。エラーが発生せずに結合テーブルがいっぱいにならない理由はまだわかりません。

于 2013-03-11T17:42:29.290 に答える