关系映射总结

一、一对一关系映射
  • 基于外键的单向一对一关系映射
          基于外键的一对一是个特殊的多对一实例。
<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>


欢迎大家的提问或纠正。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值