继承关系映射详解

继承关系映射

       继承在对象模型中是 is a(是一个)的关系,但在关系模型中,实际之间只有has a(有一个)的关系,也就是说,继承在对象模型和关系模型上是不匹配的,索性的是Hibernate提供了3中常用的继承映方案。

一.整个继承层次一张表

把整个继承层次的多个类的信息存放到一张表里。需要在表中添加一个特定字段,用这个字段的值来进行区分哪些记录是属于哪一个类的。

<hibernate-mapping

    package="com.hbsi.domain">

  

    <class name="Employee" table="employee" discriminator-value="0">

       <id name="id" column="id">

           <generator class="native"/>

       </id>

       //指定鉴别器字段,要放置在所有属性映射之前

       <discriminator column="type" type="int"></discriminator>

       <property name="name"/>

      

       <many-to-one name="depart"column="depart_id"></many-to-one>

        //用subclass映射子类,指定鉴别字段值

       <subclass name="Skiller" discriminator-value="1">

       //映射本子类的属性

       <property name="skill"></property>

       </subclass>

       <subclass name="Sales" discriminator-value="2">

       <property name="sell"></property>

       </subclass>

    </class>

</hibernate-mapping>

二.  每一个子类一张表

这种方案是把对象模型上的继承关系表示为关系模型中的外键关联,继承机构中的每个类和子类都有一张对应的数据库

<classname="Employee" table="employee">

       <id name="id" column="id">

           <generator class="native"/>

       </id>

       <property name="name"/>

       <many-to-one name="depart"column="depart_id"></many-to-one>

       //用joined—subclass元素给每个子类映射到一张表

       <joined-subclass name="Skiller"table="skiller">

       //用key元素来指定子类和父类之间通过那个字段来关联的

           <key column="employee_id"></key>

       //映射本子类的属性

           <property name="skill"></property>

       </joined-subclass>

       <joined-subclass name="Sales"table="sales">

           <key column="emplyee_id"></key>

           <property name="sell"></property>

       </joined-subclass>

   </class>

三.  每个具体类一张表

这种策略是针对每个具体类对应一张表,而且这张表的信息室完备的,它包含所有丛父类继承下来的属性映射的字段和自己的属性映射的字段

<class name="Employee"table="employee">

       <id name="id"column="id">

           <generator class="hilo"/>

       </id>

    <property name="name"/>

    <many-to-one name="depart" column="depart_id"></many-to-one>

//用union-subclass元素给每一个具体子类映射到一张表

    <union-subclass name="Skiller" table="skiller">

//映射本子类的属性

    <property name="skill"></property>

    </union-subclass>

    <union-subclass name="Sales" table="sales">

    <property name="sell"></property>

    </union-subclass>

</class>

   

总结:1.如果不需要多态查询:使用每个具体类一张表。

     2.一定要使用多态查询:子类中的属性相对较少,使用每个继承层次一张表。

   3.子类中的属性 较多,使用每个子类一张表。

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值