一、一对一关系映射
- 基于外键的单向一对一关系映射
基于外键的一对一是个特殊的多对一实例。
<many-to-one name="address" column="address_id" unique="true"></many-to-one>
- 基于外键的双向一对一关系映射
<many-to-one name="address" column="address_id" unique="true"></many-to-one>
<one-to-one name="student" property-ref="address"></one-to-one>
- 基于主键的单向一对一关系映射
<id name="id" column="id" type="integer">
<!--表示自动增长-->
<generator class="foreign">
<param name="property">address</param>
</generator>
</id>
<property name="name" />
<one-to-one name="address" constrained="true"></one-to-one>
- 基于主键的双向一对一关系映射
<id name="id" column="id" type="integer">
<!--表示自动增长-->
<generator class="foreign">
<param name="property">address</param>
</generator>
</id>
<property name="name" />
<one-to-one name="address" class="Address" constrained="true" lazy="false"></one-to-one>
<one-to-one name="student" class="Student" cascade="all"></one-to-one>
二、一对多(多对一)关系映射(一个家庭地址有多个学生)
- 单向一对多关联映射
Adress.hbm.xml
<set name="setStudent">
<key column="student_id"></key>
<one-to-many class="Student"/>
</set>
- 单向多对一关联映射
student.hbm.xml
<many-to-one name="address" column="address_id"></many-to-one>
- 双向一对多关联映射
Adress.hbm.xml
<set name="setStudent" cascade="all">
<key column="stu_id"></key>
<one-to-many class="Student"/>
</set>
student.hbm.xml
<many-to-one name="address" column="stu_id"></many-to-one>
三、多对多关联映射
- 普通多对多
Course.hbm.xml
<set name="setStudent" table="stu_course01">
<key column="course_id"></key>
<many-to-many column="student_id" class="Student"></many-to-many>
</set>
Student.hbm.xml
<set name="setCourse" table="stu_course01">
<key column="student_id"></key>
<many-to-many column="course_id" class="Course"></many-to-many>
</set>
- 基于中间表的多对多(常用)
两个一对多的映射关联
Course.hbm.xml
<set name="setStudent">
<key column="course_id"></key>
<one-to-many class="Stu_Course"/>//这个是中间表的类名
</set>
Stu_Course.hbm.xml
<many-to-one name="student" column="student_id"></many-to-one>
<many-to-one name="course" column="course_id"></many-to-one>
Student.hbm.xml
<set name="setCourse" >
<key column="student_id"></key>
<one-to-many class="Stu_Course"/>//这个是中间表的类名
</set>
欢迎大家的提问或纠正。