且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

休眠一对多问题

更新时间:2021-08-21 09:21:05

您需要将Student对象推入Phone对象:

You need to push the Student object into the Phone objects:

foreach (Phone phone : student.getStudentPhoneNumbers()) {
    phone.setStudent(student);
}

一个更典型的代码将先创建Student实例,然后添加电话号码给它。我经常实施一个方法来帮助这个,例如。 in Student.java:

A more typical piece of code would create the Student instance first, and then add the phone numbers to it. I've often implemented a method to help with this, e.g. in Student.java:

public void addPhoneNumber(Phone phone) {
    phone.setStudent(this);
    getStudentPhoneNumbers().add(phone);
}
public void addPhoneNumber(String type, String number) {
    addPhoneNumber(new Phone(type, number));
}

现在你可以说 student.addPhoneNumber home,12354),它将简单地DTRT。

So now you can say student.addPhoneNumber("home", "12354") and it will simply DTRT.