2011-07-05 162 views
1

我是Hibernate的新手,在教程http://www.vaannila.com/hibernate/hibernate-example/hibernate-mapping-one-to-many-using-annotations-1.html之後,我對該教程中的主類有個疑問。休眠更新表

我明白

 
Set phoneNumbers = new HashSet(); 
phoneNumbers.add(new Phone("house","32354353")); 
phoneNumbers.add(new Phone("mobile","9889343423")); 
Student student = new Student("Eswar", phoneNumbers); 
session.save(student); 
transaction.commit(); 

新記錄插入三個表。但是,如果這名學生得到另一個號碼

 
Phone work = new Phone("mobile","12345678"); 

我怎麼能更新PHONE和STUDENT_PHONE表。謝謝。

回答

0

您錯過了幾件事情。此代碼將工作:

Set phoneNumbers = new HashSet(); 
student.setPhoneNumbers(phoneNumbers); // Add the phone numbers to the Student 

Phone phone = new Phone("house","32354353"); 
session.save(phone); // Persist the new object 
phoneNumbers.add(phone); 

Phone phone = new Phone("mobile","9889343423"); 
session.save(phone); // Persist the new object 
phoneNumbers.add(phone); 

Student student = new Student("Eswar", phoneNumbers); 
session.save(student); 
transaction.commit(); 
+0

感謝您的回覆。可能我沒有很好地解釋我的問題。我可以讓代碼工作。我想知道的是在教程中運行主類後,STUDENT表中有一個名爲「Eswar」的學生。但是後來我們想通過添加他的工作電話號碼來更新Eswar的細節,我該怎麼處理它。我曾嘗試使用session.save(學生),但我在STUDENT表中獲得兩個「Eswar」條目。 – user200340