這種映射方式只需為繼承關系樹的Employee根類創建一張表EMPLOYEES。如圖14-4所示,在EMPLOYEES表中不僅提供和Employee類的屬性對應的字段,還要提供和它的兩個子類的所有屬型對應的字段,此外,EMPLOYEES表中需要額外加入一個字符串類型的EMPLOYEE_TYPE字段,用於區分Employee的具體類型。
<id name="id" type="long" column="ID">
<generator class="increment"/>
</id>
<property name="name" type="string" column="NAME" />
<set
name="employees"
inverse="true"
lazy="true" >
<key column="COMPANY_ID" />
<one-to-many class="mypack.Employee" />
</set>
</class>
</hibernate-mapping>
Employee.hbm.xml文件用於把Employee類映射到EMPLOYEES表,在這個映射文件中,除了需要映射Employee類本身的屬性,還需要在元素中映射兩個子類的屬性。例程14-6是Employee.hbm.xml文件的代碼。
例程14-6 Employee.hbm.xml
<hibernate-mapping >
<class name="mypack.Employee" table="EMPLOYEES">
<id name="id" type="long" column="ID">
<generator class="increment"/>
</id>
<discriminator column="EMPLOYEE_TYPE" type="string" />
<property name="name" type="string" column="NAME" />
<many-to-one
name="company"
column="COMPANY_ID"
class="mypack.Company"
/>
<subclass name="mypack.HourlyEmployee" discriminator-value="HE" >
<property name="rate" column="RATE" type="double" />
</subclass>
<subclass name="mypack.SalariedEmployee" discriminator-value="SE" >
<property name="salary" column="SALARY" type="double" />
</subclass>
</class>
</hibernate-mapping>
在Employee.hbm.xml文件中,元素指定EMPLOYEES表中用於區分Employee類型的字段為EMPLOYEE_TYPE,兩個元素用於映射HourlyEmployee類和SalariedEmployee類,元素的discriminator-value屬性指定EMPLOYEE_TYPE字段的取值。EMPLOYEES表中有以下記錄: