1.一对多
(1)两个表一对多关联(客户---订单)
customer.hbm.xml:
<id name="id" column="id" type="long">
<generator class="increment"> <!-- 主键id的生成方式为自增 -->
</generator>
</id>
<set name="orders" cascade="save-update" inverse="true">
<key column="customer_id"></key> <!-- key元素设定与所关联的持久化类对应的表的外键 -->
<one-to-many class="com.test.Order"/>
</set>
order.hbm.xml:
<id name="id" column="id" type="long">
<generator class="increment"> <!-- 主键id的生成方式为自增 -->
</generator>
</id>
<many-to-one name="customer" column="customer_id" class="com.test.Customer">
</many-to-one>
(2)一对多自身双向关联
<set name="childCategories" cascade="all" inverse="true" >
<key column="category_id"></key>
<one-to-many class="com.test.Category"/>
</set>
<many-to-one name="parentCategory" column="category_id" class="com.test.Category"></many-to-one>
2.一对一(例子:学生---身份证)
根据数据库的设计分为一下两种:
(1)共用主键id
student.hbm.xml:
<id name="id" unsaved-value="null"><!--id的产生方式是uuid.hex-->
<generator class="uuid.hex" />
</id>
<one-to-one name="cer" class="model.Certificate" fetch="join" cascade="all" /><!--映射对应的身分证对象-->
certificate.hbm.ml:
<id name="id">
<generator class="foreign">
<param name="property">stu</param>
</generator>
</id>
<one-to-one name="stu" class="model.Student" fetch="select"
constrained="true" cascade="none"/>
(2)外键关联
student.hbm.xml:
<id name="id" unsaved-value="null"><!--id的产生方式是uuid.hex-->
<generator class="uuid.hex" />
</id>
<one-to-one name="cer" class="model.Certificate" fetch="join" cascade="all" /><!--映射对应的身分证对象-->
certificate.hbm.ml:
<id name="id">
<generator class="uuid.hex" />
</id>
<many-to-one name="stu"
class="model.Student"
unique="true"
column="stu_id"
/> <!-- 唯一的多对一,实际也就变成一对一关系了 -->
3.多对多(学生---课程 通过选课表连接)
student.hbm.xml:
<id name="id" unsaved-value="null"><!--id的产生方式是uuid.hex-->
<generator class="uuid.hex" />
</id>
<set name="courses" table="student_course"
cascade="none" inverse="true">
<key column="stu_id" />
<many-to-many class="model.Course"
column="course_id" />
</set>
course.hbm.xml:
<id name="id" unsaved-value="null" ><!--id的产生方式是uuid.hex-->
<generator class="uuid.hex" />
</id>
<set name="students" table="student_course"
cascade="save-update">
<key column="course_id" />
<many-to-many class="model.Student"
column="stu_id" />
</set>