![](/img/trans.png)
[英]How to save a List of persistent objects bound to another objects with Hibernate
[英]How to make a list (containing of objects) persistent
首先,如您所見,我使用Java,特別是NetBeans IDE。 因此,我有一個Person類,它擴展了兩個類:Trainer和Athlete。
首先,我創建一個新的ArrayList list = new ArrayList();
然后,我將創建和持久化的對象填充到列表中。
Trainer tr1= new Trainer("George","White","England",5665);
Athlete ath1= new Athlete("Mairy","Willians","France",1,'f',"21/3/1988",68,172,"France");
list.add(ath1);
Athlete ath2=new Athlete("Iggy","Black","USA",2,'f',"10/4/1988",70,175,"U.S.A.");
list.add(ath2);
tr1.setAthletes(list);
(這些字段分別在培訓師和運動員課程的構造函數中定義好。
我也讓他們堅持不懈。
em2.persist(tr1);
em2.persist(ath1);
em2.persist(ath2);
但是最后,盡管運動員和培訓師堅持不懈,但我所擁有的名單卻沒有。
多數民眾贊成在我的問題開始的地方,我希望這些列表是持久的。
在這里,這些列表正在運行並經過測試,可以,但是可以在Java級別而不是ObjectDB級別使用。
我應該重新開始嗎?
有誰可以幫我解決這些問題嗎? 我真的需要幫助,這很嚴重。
PS:當然,我已經完成了所需的導入,例如
import javax.persistence.*;
import java.util.*;
EntityManagerFactory emf2 = Persistence.createEntityManagerFactory("$objectdb/db/personas2.odb");
EntityManager em2 = emf2.createEntityManager();
em2.getTransaction().begin();
em2.close();
emf2.close();
但是最后,盡管運動員和培訓師堅持不懈,但我所擁有的名單卻沒有。
一些想法:
確保commit
事務(盡管您提到實體已保留)。
如果您在Trainer
和Athlete
之間的一對多關聯是雙向的(也許顯示您的實體),請確保正確設置鏈接的“另一”側,如下所示:
Trainer tr1 = new Trainer("George","White","England",5665); Athlete ath1 = new Athlete("Mairy","Willians","France",1,'f',"21/3/1988",68,172,"France"); ath1.setTrainer(tr1); // set the other side of the link list.add(ath1); ... tr1.setAthletes(list);
或在您的實體中添加方法(在此處的Trainer
):
public void addToAthletes(Athlete athlete) { athlete.setTrainer(this); this.athletes.add(athlete); }
並將以上行替換為:
Trainer tr1 = new Trainer("George","White","England",5665); Athlete ath1 = new Athlete("Mairy","Willians","France",1,'f',"21/3/1988",68,172,"France"); tr1.addToAthletes(ath1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.