• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

[Hibernate] One-to-many batch updating?

 
Patrick Tsang
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

Hibernate version:
3.1.3

Mapping documents:
Domain objects:
DomainTeacher.java
DomainStudent.java


DB objects:
Teacher.java
private int teacherid;
private String teachername;
private Set students;
//getter and setter
-----------------------------------
teacher.hbm.xml
<class name="Teacher" table="Teacher">
<id name="teacerid" column="TeacherID" type="java.lang.Integer">
<generator class="identity" />
</id>

<property name="teachername" column="teachername" type="java.lang.String"/>
<set name="students" inverse = "true" cascade = "all">
<key column="TeacherID" /> <one-to-many class="Student"/>
</set>


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;
}

----------------------------------------
student.hbm.xml
<class name="Student" table="Student">
<composite-id>
<key-many-to-one name="Teacher" class="Teacher" column="TeacherID"/>
<key-property name="studentname" column="studentname" type="java.lang.Integer"/>
</composite-id>


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);
}

teacher.setStudents(students);
session.save(teacher);
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic