![](/img/trans.png)
[英]Can we use discriminator as many-to-one relationship in Table per class Hierarchy in Hibernate
[英]Hibernate: many-to-one relationship with "Table per concrete class with unions"
在“Java Persistence with Hibernate, Second Edition”一書中,第 6.2 節“帶有聯合的每個具體類的表”(第 120 頁)描述了一種映射類繼承的方法。
實體是:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class BillingDetails {
@Id
@GeneratedValue(generator = Constants.ID_GENERATOR)
protected Long id;
@NotNull
protected String owner;
// ...
}
和
@Entity
public class CreditCard extends BillingDetails {
@NotNull
protected String cardNumber;
@NotNull
protected String expMonth;
@NotNull
protected String expYear;
// ...
}
為從表中選擇而創建的 SQL 是:
select
ID, OWNER, EXPMONTH, EXPYEAR, CARDNUMBER,
ACCOUNT, BANKNAME, SWIFT, CLAZZ_
from
( select
ID, OWNER, EXPMONTH, EXPYEAR, CARDNUMBER,
null as ACCOUNT,
null as BANKNAME,
null as SWIFT,
1 as CLAZZ_
from
CREDITCARD
union all
select
id, OWNER,
null as EXPMONTH,
null as EXPYEAR,
null as CARDNUMBER,
ACCOUNT, BANKNAME, SWIFT,
2 as CLAZZ_
from
BANKACCOUNT
) as BILLINGDETAILS
到目前為止,表模式對我來說很清楚。
現在,我想擴展這個模式。 我想添加一個新實體Purchase
,以便每個BillingDetails
都有很多Purchase
。
是否可以在保持BillingDetails
層次結構的基本架構的同時實現它?
如果可能的話,你能描述一下擴展模式的表嗎?
我不一定對通過 Hibernate annotations/XML 描述模式的方式感興趣(以防它不能被 Hibernate annotations/XML 映射),而是對可以描述這種關系的基本表結構和相關 SQL 感興趣。
您想要的是一對多關系BillingDetails 1 - * Purchase
。 互聯網上有很多這樣的例子。
在數據庫級別上,您需要一個外鍵 (FK),即從Purchase
表到BillingDetails
的引用。 這意味着在Purchase
中,您有一個“billing_details_id”列,它應該指向現有的計費詳細信息記錄。
可以在不更改BillingDetails
的情況下實現此目的,但您可能希望更新BillingDetails
以讓 Hibernate 知道它與Purchase
是多對一的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.