表设计:
有一张中间表,中间表中有两张关联表的外键
如:student与teacher
Student:
package cn.framelife.mvc.entity; import java.util.Set; public class Student { private Integer id; private String name; private Set<Teacher> teachers; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Teacher> getTeachers() { return teachers; } public void setTeachers(Set<Teacher> teachers) { this.teachers = teachers; } }
Teacher:
package cn.framelife.mvc.entity; import java.util.Set; public class Teacher { private Integer id; private String name; private Set<Student> students; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Student> getStudents() { return students; } public void setStudents(Set<Student> students) { this.students = students; } }
Student.hbm.xml:
<hibernate-mapping> <class name="cn.framelife.hibernate.entity.Student" table="student"> <id name="id" type="java.lang.Integer"> <column name="id" /> <generator class="native" /> </id> <property name="name" type="java.lang.String"> <column name="s_name" length="45" not-null="true" /> </property> <set name="teachers" table="s_t" cascade="all"> <key column="student_id"/> <many-to-many column="teacher_id" class="cn.framelife.hibernate.entity.Teacher"></many-to-many> </set> </class> </hibernate-mapping>
Teacher.hbm.xml:
<hibernate-mapping> <class name="cn.framelife.hibernate.entity.Teacher" table="teacher" catalog="hibernate"> <id name="id" type="java.lang.Integer"> <column name="id" /> <generator class="native" /> </id> <property name="name" type="java.lang.String"> <column name="t_name" length="45" not-null="true" /> </property> <set name="students" table="s_t" > <key column="teacher_id"/> <many-to-many column="student_id" class="cn.framelife.hibernate.entity.Student"></many-to-many> </set> </class> </hibernate-mapping>
增加:
Student s1 = new Student(); s1.setName("s10"); Student s2 = new Student(); s2.setName("s11"); Set<Teacher> set = new HashSet<Teacher>(); Teacher t1 = new Teacher(); t1.setName("t10"); Teacher t2 = new Teacher(); t2.setName("t11"); set.add(t1); set.add(t2); //设置学生与老师的的关系 s1.setTeachers(set); s2.setTeachers(set); //增加两个学生,同时会把老师也加到数据库中 session.save(s1); session.save(s2);