My goal: everytime when I update the teacher, I will reassign the students to this teacher, for example, Case A: Teacher 1 have student 1,2,3, now I want to assign 4 to this teacher, but remove 1,2,3. Case B: Teacher 1 have student 1,2,3, now I want to assign 1,4,5 to this teacher
My question is, Do I need to run the query (marked in the //NOTE below),or hibernate itself will figure that out?I tried that a couple times, it seems I have to do the deletion manually, or I just doing something wrong?
Student.java private Teacher teacher; private studentname; //getter and setter
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Student)) return false; final Student stu = (Student) o; if (!this.teacher.equals(stu.getTeacher()) return false; if (!studentname.equals(stu.getStudentname)) return false; return true; }
public int hashCode() { int result; result = this.teacher.hashCode(); result = 29 * result + this.studentname.hashCode(); return result; }
Code between sessionFactory.openSession() and session.close(): TeacherDAO:
public void updateTeacher(DomainTeacher domainTeacher ){ int teacherId = domainTeacher.getTeacherid(); Teacher teacher = (Teacher)session.get(Teacher.class, teacherid) teacher.setTeachername(domainTeacher.getTeachername);
//NOTE: Delete the exisiting students Query q = session.createQuery("DELETE FROM Student WHERE teacherid = :teacherId"); q.setInteger("teacherId",teacherId); q.executeUpdate();
Set<Student> students = new HashSet<Student>(); Set<DomainStudent> domainStudents = domainTeacher.getDomainStudents(); for(DomainStudent ds: domainStudents){ Student student = new Student(); student.setTeacher(teacher); student.setStudentname(ds.getStudentname()); students.add(student); }