![](/img/trans.png)
[英]difference of owned one-to-many relationship between GAE/J low level datastore API and DataNucleus JDO
[英]GAE JPA DataNucleus One-to-Many object creation
假设一个所有者拥有一组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
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;
非常感谢你提前!
温馨问候,
贾森
您的关联是双向的,但您没有正确设置链接的两侧,如错误消息所报告的那样。 你的代码应该是:
...
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.