I am working for a client so I had to change the file names etc. However while trying to do these changes for you, I have got a bit closer to the root of the problem.
I have a service class and a DAO class.
Code:
public class TeacherDaoImpl extends JpaDaoSupport implements TeacherDao {
public Teacher saveUpdateTeacherStudent(Teacher teacher) {
return getJpaTemplate().merge(teacher);
}
public Teacher getTeacher(int id) {
Teacher teacher = getJpaTemplate().find(Teacher.class, id);
return teacher;
}
public Teacher attachStudentToTeacher(int teacherId, Student student) {
Teacher teacher = getTeacher(teacherId);
teacher.addOrUpdateStudent(student);
return teacher;
}
...
}
In my sevice class (where spring transaction are configured), this does not save the relation between teacher and student, but saves the student in its table.
Code:
Teacher teacher = teacherDao.getTeacher(0);
Student student = new Student();
student.setName("Petter Solberg");
teacher.addOrUpdateStudent(student);
teacherDao.saveUpdateTeacherStudent(teacher);
However if I use the other dao method (attachStudentToTeacher) then everything works fine:
Code:
teacherDao.attachStudentToTeacher(0, student);
So this means I have misunderstood something regarding scope of the persistenceContext. Shouldn't it be able to see that the student collection has been changed, when it tries to save the parent teacher?