继承关系树的每个具体类对应一张表

时间:2021-12-04 14:46:13

继承关系映射方式一:继承关系树的每个具体类对应一张表

实体对象:

Employee: Integer id; String name; Company company;(不创建表)

Company: Integer id;String name;

HourlyEmployees extendsEmployee:Integer id;String name;Double rate;

SalariedEmployees extendsEmployee:Integer id;String name;Double salary;

关系模型:

company表:

继承关系树的每个具体类对应一张表

houry_employees表:

继承关系树的每个具体类对应一张表

salaried_employees表:

继承关系树的每个具体类对应一张表

映射文件:

Company_hbm.xml

<hibernate-mapping>

    <class name="bean.Company"table="company" catalog="addressbooksample">

        <id name="id"type="java.lang.Integer">

            <column name="ID"/>

            <generator class="native"/>

        </id>

        <property name="name"type="java.lang.String">

            <column name="name"length="20" />

        </property>

    </class>

</hibernate-mapping>

HourlyEmployees.hbm.xml:(映射:自身属性,继承属性,关联关系属性)

<hibernate-mapping package="bean">

    <class name="bean.HourlyEmployees"table="hourly_employees" catalog="addressbooksample">

        <id name="id"type="java.lang.Integer">

            <column name="ID"/>

            <generator class="native"/>

        </id>

        <property name="name"type="java.lang.String">

            <column name="name"length="20" />

        </property>

        <property name="rate"type="java.lang.Double">

            <column name="rate"precision="15" scale="3"/>

        </property>

        <many-to-one name="company"column="COMPANY_ID" class="Company" cascade="save-update"lazy="false"/>

    </class>

</hibernate-mapping>

 

Salaried.hbm.xml: (映射:自身属性,继承属性,关联关系属性)
<hibernate-mappingpackage="bean">

    <class name="bean.SalariedEmployees"table="salaried_employees" catalog="addressbooksample">

        <id name="id"type="java.lang.Integer">

            <column name="ID"/>

            <generator class="native"/>

        </id>

        <property name="name"type="java.lang.String">

            <column name="name"length="20" />

        </property>

        <property name="salary"type="java.lang.Double">

            <column name="salary"precision="15" scale="3"/>

        </property>

        <many-to-one name="company"column="COMPANY_ID" class="Company" cascade="save-update"/>

    </class>

</hibernate-mapping>

 

 

————————————————总结———————————————————————

 

缺点:每个具体类对应一个表,这些表中包含重复字段;如果要查询父类的对象,必须查询所有具体的子类对应的表;如果父类的属性发生变化,必须修改所有具体的子类对应的表;不支持多态查询;

优点:符合关系数据库的设计