annotation方式:
@Entity
public class Teacher {
private int id;
private Set<Student> students = new HashSet<Student>();
@ManyToMany
@JoinTable(name = "t_s",
joinColumns={@JoinColumn(name = "teacher_id")},
inverseJoinColumns = {@JoinColumn(name = "student_id")})
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
@Entity
public class Student {
private int id;
private Set<Teacher> teachers = new HashSet<Teacher>();
@ManyToMany(mappedBy = "students")
public Set<Teacher> getTeachers() {
return teachers;
}
public void setTeachers(Set<Teacher> teachers) {
this.teachers = teachers;
}
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
xml方式:
<hibernate-mapping package="hibernate">
<class name="hibernate.Teacher">
<id name="id" >
<generator class="native"/>
</id>
<set name="students" table="t_s">
<key column="teacher_id"></key>
<many-to-many class="hibernate.Student" column="student_id"/>
</set>
</class>
</hibernate-mapping>
<hibernate-mapping package="hibernate">
<!--table 属性不配就是默认-->
<class name="hibernate.Student" >
<id name="id" >
<generator class="native"/>
</id>
<set name="teachers" table="t_s">
<key column="student_id"></key>
<many-to-many class="hibernate.Teacher" column="teacher_id"/>
</set>
</class>
</hibernate-mapping>