4

Owner が Watch(es) のコレクションを持っているとしましょう。

ウォッチを作成し、新しく作成したウォッチを既存の所有者のウォッチ コレクション (配列リスト) に追加しようとしています。

私の方法は次のとおりです。

public void add(String ownerName, String watchName) {

    Owner o = new OwnerDAO().retrieve(ownerName); //retrieves owner object without fail

    EntityManager em = EMF.get().createEntityManager();
    EntityTransaction t = em.getTransaction();

    Watch w = new Watch(watchName);

    Owner owner = em.merge(o);

    t.begin();
    owner.getWatches().add(w);
    t.commit();

    em.close();

}

コードはローカル GAE 環境では問題なく動作しますが、オンライン GAE 環境では次の問題が発生しました。

org.datanucleus.store.mapped.scostore.FKListStore$1 fetchFields: Object "package.Owner@2b6fc7" has a collection "package.Owner.watches" yet element "package.Watch@dcc4e2" doesnt have the owner set. Managing the relation and setting the owner.

この問題を解決する方法を教えてください。ありがとうございました!

エンティティ:

オーナー:

@id
private String name;

@OneToMany(mappedBy = "owner",
targetEntity = Watch.class, cascade = CascadeType.ALL)
private List<Watch> watches= new ArrayList<Watch>();

時計:

@id
private String name;

@ManyToOne()
private Owner owner;

事前にどうもありがとうございました!

からだに気をつけてね、

ジェイソン

4

1 に答える 1

3

関連付けは双方向ですが、エラー メッセージで報告されているように、リンクの両側を適切に設定していません。コードは次のようになります。

...
owner.getWatches().add(w);
w.setOwner(owner); //set the other side of the relation
t.commit();

典型的なパターンは、次のように防御的なリンク管理方法を使用して、アソシエーションの両側を正しく設定することです ( をOwner参照)。

public void addToWatches(Watch watch) {
    watches.add(watch);
    watch.setOwner(this);
}

そして、あなたのコードは次のようになります:

...
owner.addToWatches(w);
t.commit();
于 2010-09-23T19:37:59.757 に答える