Hibernate实战_30(每个子类一张表)
不同于我们最先映射的每个具体类一张表的策略,此处的表仅仅包含了每个非继承的属性(由子类本身声明的每个属性)以及也是超类表的外键的主键的列。
这一策略的主要好处在于,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>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。