Hibernate实战_30(每个子类一张表)

来源:互联网 发布:王侯将相焉有种乎出自 编辑:程序博客网 时间:2024/06/05 21:55
第四种方案是把继承关系表示为相关的外键关联。声明持久化属性的每个类/子类(包括抽象类甚至接口)都有它自己的表。
不同于我们最先映射的每个具体类一张表的策略,此处的表仅仅包含了每个非继承的属性(由子类本身声明的每个属性)以及也是超类表的外键的主键的列。
这一策略的主要好处在于,SQL Schema被标准化了。Schema演变和完整性约束定义很简单。对一个特定子类的多态关联可能被表示为引用这个特定子类的表的一个外键。

在Hibernate中,用<joined-subclass>元素给每个子类映射创建一张表。

<hibernate-mapping package="cn.jbit.hibernate.entity4"><class name="BillingDetails6" table="BILLING_DETAILS6"><id name="id" column="BILLING_DETAILS_ID" type="integer"><generator class="native"/></id><property name="owner"><column name="OWNER" not-null="true"/></property><joined-subclass name="CreditCard6" table="CREDIT_CARD6"><key column="CREDIT_CARD_ID" /><property name="number" column="CC_NUMBER" length="20" not-null="true"/><property name="expMonth" column="EXP_MONTH" length="20" not-null="true"/><property name="expYear" column="EXP_YEAR" length="20" not-null="true"/></joined-subclass></class></hibernate-mapping>

JPA中也有这个映射策略,即JOINED策略:
@Entity@Table(name = "BILLING_DETAILS7")@Inheritance(strategy = InheritanceType.JOINED)public abstract class BillingDetails7 {@Id@GeneratedValue@Column(name = "BILLING_DETAILS_ID", nullable = false)private Integer id;@Column(name = "OWNER", nullable = false)private String owner;}
显式地指定列名,Hibernate就知道如何把表联结到一起。
@Entity@Table(name = "CREDIT_CARD7")//子表主键名称,对应于BillingDetails7表外键@PrimaryKeyJoinColumn(name="CREDIT_CARD_ID")public class CreditCard7 extends BillingDetails7 {@Column(name = "CC_NUMBER", nullable = false)private String number;@Column(name = "EXP_MONTH", nullable = false)private String expMonth;@Column(name = "EXP_YEAR", nullable = false)private String expYear;}
下面是JPA XML描述符中与之相当的映射:
<entity class="cn.jbit.hibernate.entity4.BillingDetails4" access="FIELD"><inheritance strategy="JOINED"/><attributes><id name="id"><column name="BILLING_DETAILS_ID" nullable="false"/><generated-value strategy="AUTO"/></id><basic name="owner"><column name="OWNER" nullable="false"/></basic></attributes></entity><entity class="cn.jbit.hibernate.entity4.CreditCard4" access="FIELD"><primary-key-join-column name="CREDIT_CARD_ID"/><attributes><basic name="number"><column name="CC_NUMBER" nullable="false"/></basic><basic name="expMonth"><column name="EXP_MONTH" nullable="false"/></basic><basic name="expYear"><column name="EXP_YEAR" nullable="false"/></basic></attributes></entity>
1 0
原创粉丝点击