标签:
1.Annotation
@Entity public class Teacher { private String name; private int id; private Set<Student> students; @ManyToMany @JoinTable(name="t_s", //join column points to this.id; joinColumns={@JoinColumn(name="teacher_id")}, //inverseJoinColumns points to id of student class inverseJoinColumns={@JoinColumn(name="stu_id")} ) public Set<Student> getStudents() { return students; } public void setStudents(Set<Student> students) { this.students = students; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Id public int getId() { return id; } public void setId(int id) { this.id = id; } } @Entity @Table(name="t_student") public class Student { private int age; private int classID; private String name; private int id; private Set<Teacher> teachers; @ManyToMany(mappedBy="students") public Set<Teacher> getTeachers() { return teachers; } public void setTeachers(Set<Teacher> teachers) { this.teachers = teachers; } public int getClassID() { return classID; } public void setClassID(int classID) { this.classID = classID; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Id public int getId() { return id; } public void setId(int id) { this.id = id; } }
2.XML
Junction table‘s name and FK ,PK must match to each other!!
<hibernate-mapping package="com.hibernate.model"> <class name="Teacher" table="T_Teacher"> <id name="id"></id> <property name="name"></property> <!-- table="xx" xx is name of junction table --> <set name="students" table="tea_stu"> <key column="teacher_Id"></key> <many-to-many class="com.hibernate.model.Student" column="student_id"/> </set> </class> <class name="Student" table ="S_Student"> <id name="id"></id> <property name="name"></property> <property name="age"></property> <property name="classID"></property> <set name="teachers" table="tea_stu"> <key column="student_Id"></key> <many-to-many class="com.hibernate.model.Student" column="teacher_id"/> </set> </class>
Hibernate Many-to-Many Bidirectional mapping
标签:
原文地址:http://www.cnblogs.com/fifi043/p/4910384.html