1

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.

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
Joe209
  • 65
  • 5

1 Answers1

0
  1. If myClass is detached but the studentList was already intialized:

    Override
    @Transactional
    public void addStudentToClass(MyClass myClass, Student student) {
        myClass.getStudentList().add(student);
        classDao.update(myClass);
    }
    
  2. If myClass is detached but the studentList has not been previously initialized:

    Override
    @Transactional
    public void addStudentToClass(MyClass myClass, Student student) {
        MyClass attachedMyClass = classDao.merge(myClass);
        attachedMyClass.getStudentList().add(student);
    }
    
Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
  • Thank you for the response; however, I have set fetch lazy on the list, myClass.getStudentList().add(student) would throw lazyinitializedException, I think – Joe209 Jan 10 '15 at 23:25
  • Thank you. I just look at session api for merge and it exactly what I am looking for. – Joe209 Jan 10 '15 at 23:44