新手上路之Hibernate(5):繼承映射

之前的幾篇文章主要介紹的是關係映射。之所以用好幾篇的文章來介紹關係映射,其重要性與常用行可見一斑。還有一種映射,也就是今天要介紹的——繼承映射,也是很重要的一種映射模式。

一、繼承映射的三種策略

繼承映射的實現有三種策略:

      1、單表繼承。每棵類繼承樹使用一個表。

      2、具體表繼承。每個子類一個表。

      3、類表繼承。每個具體類一個表。

下面將通過實例來具體說明這三種策略。我們以Animal類、Pig類、Bird類來講解,三者的關係如下圖:


雖然說是三種策略,但是他們都是繼承映射,所以三個實體是不變的:子類(Pig、Bird)繼承父類(Animal),並且具有自己特有的屬性。

Animal類:

public class Animal {
	private int id;
	private String name;
	private Boolean sex;
	//省略各個屬性的get、set方法
}

Bird類

public class Bird extends Animal{
	private int height;
	//省略get、set方法
}

Pig類

public class Pig extends Animal{
	private int weight;
	//省略get、set方法
}

1、單表繼承。

最終結果:只生成一個表,但是有一個鑑別字段:type


映射配置如下:Extends.hbm.xml

<hibernate-mapping>
	<class name="com.example.hibernate.Animal" table="t_animal">
		<id name="id">
			<generator class="native"/>
		</id>
		
		<discriminator column="type" type="string"></discriminator>
		
		<property name="name"/>
		<property name="sex"/>
		
		<subclass name="com.example.hibernate.Pig" discriminator-value="P">
			<property name="weight"/>
		</subclass>
		
		<subclass name="com.example.hibernate.Bird" discriminator-value="B">
			<property name="height"/>
		</subclass>
		
	</class>
</hibernate-mapping>

2、具體表繼承

最終結果:生成三個表。


每個表中的具體數據:


對應的映射配置:

<hibernate-mapping>
	<class name="com.example.hibernate.Animal" table="t_animal">
		<id name="id">
			<generator class="native"/>
		</id>
		<property name="name"/>
		<property name="sex"/>
		
	<joined-subclass name="com.example.hibernate.Pig" table="t_pig">
		<key column="pid"/>
		<property name="weight"/>
	</joined-subclass>
		<joined-subclass name="com.example.hibernate.Bird" table="t_bird">
		<key column="bid"/>
		<property name="height"/>
	</joined-subclass>
		
	</class>
</hibernate-mapping>

3、類表繼承

最終結果:生成兩個表


映射配置:

<hibernate-mapping>
	<class name="com.example.hibernate.Animal" table="t_animal" abstract="true">
		<id name="id">
			<generator class="assigned"/>
		</id>
		<property name="name"/>
		<property name="sex"/>
		
	<union-subclass name="com.example.hibernate.Pig" table="t_pig">
		<property name="weight"/>
	</union-subclass>
	
	<union-subclass name="com.example.hibernate.Bird" table="t_bird">
		<property name="height"/>
	</union-subclass>
		
	</class>
</hibernate-mapping>

總結:以上就是繼承映射的三種策略。三種策略之間各有長短:

           方式一:表中存在冗餘字段。但是數據操作效率較高(都在同一張表中)。

           方式二:層次非常清楚。但是如果繼承層次太多的話,數據操作的效率明顯不如方式一。

           方式三:不能使用自增長,只能手動分配主鍵。

因此建議使用方式一。如果繼承的層次很少,可以使用方式二。


發佈了108 篇原創文章 · 獲贊 59 · 訪問量 106萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章