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>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值