9.1.1. 每个类分层结构一张表(Table per class hierarchy)
假设我们有接口Payment
和它的几个实现类: CreditCardPayment
, CashPayment
, 和ChequePayment
。则“每个类分层结构一张表”(Table per class hierarchy)的映射代码如下所示:
<class name="Payment" table="PAYMENT">
<id name="id" type="long" column="PAYMENT_ID">
<generator class="native"/>
</id>
<discriminator column="PAYMENT_TYPE" type="string"/>
<property name="amount" column="AMOUNT"/>
...
<subclass name="CreditCardPayment" discriminator-value="CREDIT">
<property name="creditCardType" column="CCTYPE"/>
...
</subclass>
<subclass name="CashPayment" discriminator-value="CASH">
...
</subclass>
<subclass name="ChequePayment" discriminator-value="CHEQUE">
...
</subclass>
</class>
采用这种策略只需要一张表即可。它有一个很大的限制:要求那些由子类定义的字段, 如CCTYPE
,不能有非空(NOT NULL)
约束。