如何在hibernate
o表中建模主键也是外键
作为此架构:
CREATE TABLE policies (
policy_id int,
date_issued datetime,
-- // other common attributes ...
);
CREATE TABLE policy_motor (
policy_id int,
vehicle_reg_no varchar(20),
-- // other attributes specific to motor insurance ...
FOREIGN KEY (policy_id) REFERENCES policies (policy_id)
);
CREATE TABLE policy_property (
policy_id int,
property_address varchar(20),
-- // other attributes specific to property insurance ...
FOREIGN KEY (policy_id) REFERENCES policies (policy_id)
);
答案 0 :(得分:2)
当然可以。这对于您可以拥有的一对一关联非常有用:
@Id
@Column(name="policy_id")
private policyId;
@MapsId
@OneToOne
@JoinColumn(name = "policy_id")
private Policy policy;
您可以在主表上使用AUTO-INCREMENT,这意味着您需要在JPA / Hibernate中使用IDENTITY生成器。
@MapsId允许您与实体标识符属性共享同一SQL列。它指示Hibernate使用此列来解析@OneToOne
或@ManyToOne
关联。变更应始终通过@Id属性传播,而不是传播到一边(在插入/更新期间被忽略)。