簡體   English   中英

GAE JPA DataNucleus一對多對象創建

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM