一个老师对应多个学生,一个学生对应多个老师
数据库设计: 学生表,老师表,中间表(t_id,s_id)
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;
@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>
</class>
</hibernate-mapping>