[英]Hibernate: many-to-one relationship with "Table per concrete class with unions"
In the book "Java Persistence with Hibernate, Second Edition", section 6.2 "Table per concrete class with unions" (p.120) it describes one way to map class inheritance.在“Java Persistence with Hibernate, Second Edition”一书中,第 6.2 节“带有联合的每个具体类的表”(第 120 页)描述了一种映射类继承的方法。
The entities are:实体是:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class BillingDetails {
@Id
@GeneratedValue(generator = Constants.ID_GENERATOR)
protected Long id;
@NotNull
protected String owner;
// ...
}
and和
@Entity
public class CreditCard extends BillingDetails {
@NotNull
protected String cardNumber;
@NotNull
protected String expMonth;
@NotNull
protected String expYear;
// ...
}
The SQL created to select from the tables is:为从表中选择而创建的 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
So far the table schema is clear to me.到目前为止,表模式对我来说很清楚。
Now, I want to extend this schema.现在,我想扩展这个模式。 I want to add a new entity, Purchase
, so that there are many Purchase
s for every BillingDetails
.我想添加一个新实体Purchase
,以便每个BillingDetails
都有很多Purchase
。
Is it possible to implement it while keeping the basic schema of the BillingDetails
hierarchy?是否可以在保持BillingDetails
层次结构的基本架构的同时实现它?
If it's possible, can you describe the tables of the extended schema?如果可能的话,你能描述一下扩展模式的表吗?
I'm not necessarily interested in a way to describe the schema by Hibernate annotations/XML (in case that it cannot be mapped by Hibernate annotations/XML), but in the basic table structure and related SQL that can describe such a relationship.我不一定对通过 Hibernate annotations/XML 描述模式的方式感兴趣(以防它不能被 Hibernate annotations/XML 映射),而是对可以描述这种关系的基本表结构和相关 SQL 感兴趣。
What you want is one-to-many relation BillingDetails 1 - * Purchase
.您想要的是一对多关系BillingDetails 1 - * Purchase
。 There are tons of examples for this over the internet.互联网上有很多这样的例子。
On a database level you would need a foreign key (FK), ie, a reference from Purchase
table to BillingDetails
.在数据库级别上,您需要一个外键 (FK),即从Purchase
表到BillingDetails
的引用。 Meaning that in Purchase
you have a column "billing_details_id" which should point to the existing billing details record.这意味着在Purchase
中,您有一个“billing_details_id”列,它应该指向现有的计费详细信息记录。
It is possible to achieve this without changing the BillingDetails
but you might want to update BillingDetails
to let Hibernate know that it is many-to-one to Purchase
.可以在不更改BillingDetails
的情况下实现此目的,但您可能希望更新BillingDetails
以让 Hibernate 知道它与Purchase
是多对一的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.