(1)N--N单向(多对多单向) 多对多的关系,一定要找个中间表进行管理
第一步:类 对象之间的关系映射
t_teacher(id,name,age) --教师表
t_student(id,name,age) --学生表
t_teacher_student(t_id,s_id) --教师学时关系表
public class Teacher {
private int id;
private String name;
private int age;
private Set<Student> students;
}
public class Student {
private int id;
private String name;
private int age;
}
第二步:xml的配置
<class name="Teacher" table="t_teacher">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="name" unique="true" not-null="true" column="name" length="32"/>
<property name="age" column="age" length="32"/>
<set name="students" table="t_teacher_student" cascade="save-update">
<key column="t_id"></key>
<many-to-many class="Student" column="s_id"></many-to-many>
</set>
</class>
<class name="Student" table="t_student">
<id name="id" column="id">
<generator class="native">
</generator>
</id>
<property name="name" unique="true" not-null="true" column="name" length="32"/>
<property name="age" column="age" length="32"/>
</class>
(1)N--N双向(多对多双向) 多对多的关系,一定要找个中间表进行管理
第一步:类 对象之间的关系映射
t_teacher(id,name,age) --教师表
t_student(id,name,age) --学生表
t_teacher_student(t_id,s_id) --教师学时关系表
public class Teacher {
private int id;
private String name;
private int age;
private Set<Student> students;
}
public class Student {
private int id;
private String name;
private int age;
private Set<Teacher> teachers; // 增加了Teacher的集合
}
第二步:xml的配置(多对多的双向,两边写法一样的)
<class name="Student" table="t_student">
<id name="id" column="id">
<generator class="native">
</generator>
</id>
<property name="name" unique="true" not-null="true" column="name" length="32"/>
<property name="age" column="age" length="32"/>
-- 增加了set配置
<set name="teachers" table="t_teacher_student" cascade="save-update">
<key column="s_id"></key>
<many-to-many class="Teacher" column="t_id"></many-to-many>
</set>
</class>
<class name="Teacher" table="t_teacher">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="name" unique="true" not-null="true" column="name" length="32"/>
<property name="age" column="age" length="32"/>
<set name="students" table="t_teacher_student" cascade="save-update">
<key column="t_id"></key>
<many-to-many class="Student" column="s_id"></many-to-many>
</set>
</class>