4

假设所有者有一个 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();

一个典型的模式是使用防御性链接管理方法来正确设置关联的双方,像这样(in Owner):

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

你的代码会变成:

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