GAE JPA DataNucleus一对多对象创建

时间:2010-09-23 19:03:32

标签: google-app-engine jpa datanucleus

假设所有者拥有一组Watch(es)。

我正在尝试创建手表并将新创建的手表添加到现有所有者的手表集合(arraylist)。

我的方法如下:

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;

非常感谢你!

最热烈的问候,

杰森

1 个答案:

答案 0 :(得分: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();