Hibernate 支持三种继承映射策略

1,subclass 元素映射子类:用一张表存储整个继承树的全部实例。
2,joined-subclass元素映射子类:继承树的每层实例对应一张表,且基类的表中保存所有子类的公有列,因此如需创建子类实例,总是需要查询基类的表数据,其子类所在深度越深,查询涉及到的表就越多。
3,unioned-subclass元素映射子类:继承树的每层实例对应一张表,每层的实例完整地保存在对应的表中,表中的每条记录即可对应一个实例。关于继承策略的选择,建议使用unioned-subclass的继承映射策略,理由如下。使用subclass 的映射策略时,因为整个继承树的全部实例都保存在一张表内,因此子类新增的数据列都不可增加非空约束,即使实际需要非空约束也不行,因为父类实例对应的记录根本没有该列,这将导致数据库的约束降低,同时也增加数据冗余,可以说这是最差的映射策略。
       使用joined-subclass 映射策略可以避免上面的问题,但使用这种映射策略时,如需查询多层下的子类,可能要访问的表数据过多,影响性能。而使用unioned-subclass 的映射策略则可以避免上面的两个问题。一旦映射了合适的继承策略, Hibernate 完全可以理解多态查询。即查询Parent 类的实例时,所有Parent 子类的实例也可被查询到。

Employee 和Manager 的映射文件,关系:Manager implements Emloyee
<?xml version="1.0"?>
<!-- Hibernate 映射文件的文件头,包含DTD 等信息-->
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.O.dtd" >
    <!-- Hibernate映射文件的根元素-->
    <hibernate-mapping package="com.xiaogang.model">
    <!-- 映射持久化类Employee -->
      <class name="Employee" table="emp_table">
        <!-- 映射标识属性 -->
        <id name="id" type="integer" column="emp_id">
         <!-- 指定主键生成器策略 -->
         <generator class="identity" />
        </id>
    <!-- 一映射普通属性name -->
    <property name="name" column="emp_name" type="string" not-null="true" length="50" unique="true"/>
   
    <!-- 一映射普通属性pass -->
    <property name="pass" column="emp-pass" type="string" not-null="true" length="50"/>
   
    <!-- 映射普通属性salary -->
    <property name="salary" column="emp_salary" type="double" not-null="true" />
   
    <!-- 映射关联的持久化类: Manager -->
    <many-to-one name="manager" column="mgr_id" lazy="false"/>
   
    <!-- 映射l-N 的关联关系: Attend -->
    <set name="attends"  inverse="true ">
        <key column="emp_id" />
        <one-to-many class="Attend"/>
    </set>
   
    <!-- 映射l-N 的关联关系: Payment -->
    <set name="payments" inverse="true">
        <key column="emp_id" />
        <one-to-many class="Payment"/>
    </set>
   
    <!-- 映射子类: Manager, 使用joined_subclass -->
        <joined-subclass name="Manager" table="mgr_table">
            <!-- 映射标识属性,该属性与父类的标示属性对应,无需主键生成器 -->
            <key column="mgr_id"/>
            <!--  映射普通属性dept -->
            <property name="dept" column="dept_name" type="string" not-null="true" length="50"/>
            <!--  映射l-N 关联关系,子类与父类具有关联-->
            <set name="employees" inverse="true">
                <key column="mgr_id" />
                <one-to-many class="Employee"/>
            </set>
            <!-- 映射l-N 关联关系 -->
            <set name="checks" inverse="true" >
                <key column="mgr_id" />
                <one-to-many class="CheckBack"/>
            </set>
        </joined-subclass>
    </class>
    </hibernate-mapping>

你可能感兴趣的:(Hibernate,.net,xml)