读书人

Hibernate关系投射(N-N)多对多

发布时间: 2012-09-09 09:27:54 作者: rapoo

Hibernate关系映射(N--N)多对多

(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 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 column="s_id"></many-to-many>
??? ??? </set>?? ???
??? </class>

?

??? <class name="Student" table="t_student">
??? ??? <id name="id" column="id">
??? ??? ??? <generator 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 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 column="t_id"></many-to-many>
??? ??? </set>
??? </class>

?

??? <class name="Teacher" table="t_teacher">
??? ??? <id name="id" column="id">
??? ??? ??? <generator 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 column="s_id"></many-to-many>
??? ??? </set>
??? </class>

读书人网 >软件架构设计

热点推荐