package cn.edu.hpu.many2many; import java.util.HashSet; import java.util.Set; public class Student { private int id; private String name; private Set<Teacher> teachers=new HashSet<Teacher>(); public Set<Teacher> getTeachers() { return teachers; } public void setTeachers(Set<Teacher> teachers) { this.teachers = teachers; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package cn.edu.hpu.many2many; import java.util.HashSet; import java.util.Set; import cn.edu.hpu.many2many.Student; public class Teacher { private int id; private String name; private Set<Student> students=new HashSet<Student>(); //选择set的原因是因为,set互相之间不会有重复的 //跟数据库模型比较匹配 public int getId() { return id; } public void setId(int 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; } }
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.edu.hpu.many2many"> <class name="Student" table="xm_student" dynamic-update="true"> <!-- 主键 这里的主键名字刚好也是'id'--> <id name="id" column="id"> <generator class="native"></generator> </id> <property name="name"></property> <set name="teachers" table="t_s"> <key column="student_id"></key><!-- 指定关联字段的名字叫什么 --> <many-to-many class="cn.edu.hpu.many2many.Teacher" column="teacher_id"/> </set> </class> </hibernate-mapping>
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.edu.hpu.many2many"> <class name="Teacher" table="xm_teacher" dynamic-update="true"> <!-- 主键 这里的主键名字刚好也是'id'--> <id name="id" column="id"> <generator class="native"></generator> </id> <property name="name"></property> <set name="students" table="t_s"> <key column="teacher_id"></key><!-- 指定关联字段的名字叫什么 --> <many-to-many class="cn.edu.hpu.many2many.Student" column="student_id"/> </set> </class> </hibernate-mapping>
<mapping resource="cn/edu/hpu/many2many/Student.hbm.xml"/> <mapping resource="cn/edu/hpu/many2many/Teacher.hbm.xml"/>
references xm_student (id)
转载请注明出处:http://blog.csdn.net/acmman