I have looked into several example on hibernate one-to-many unidirectonal relation, and wonder that how can I add a new object into an existing list.
Assume that I have a class MyClass
@OneToMany(fetch=FetchType.LAZY, cascade={
CascadeType.PERSIST,
CascadeType.REMOVE})
@org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
@JoinTable(name="enrolled_student",
joinColumns = {@JoinColumn(name="Class_ID")},
inverseJoinColumns = {@JoinColumn(name="STUDENT_ID") })
public List<Student> getStudentList() { return studentList;}
public void setStudentList(List<Student> studentList) { this.studentList = studentList;}
private List<Student> List;
If I have a list of students such as s1, s2, s3. And now I want to to add student s4 into the class. How can I do that?
I have tried to do as:
@Override
@Transactional
public void addStudentToClass(MyClass class, Student student) {
List<student> list = new ArrayList<Student>();
list.add(student);
budget.setStudentList(list);
classDao.update(budget);
}
But it doesnt work as I expected. It erased all the existing student s1, s2, s3, then persist s4.