在 JPA/Hibernate 中使用 PK 作为 FK

Use the PK as FK in JPA/Hibernate

我如何在 hibernate o table 中建模,其中主键也是外键

作为此架构:

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)
);
  1. 这在休眠映射中是否可行,或者最好是分开 他们并使用新的 PK ?
  2. 而且如果我在 main table
  3. 上使用自动增量也没关系

当然可以。这对于一对一关联很有用,您可以拥有:

@Id
@Column(name="policy_id")
private policyId;

@MapsId
@OneToOne
@JoinColumn(name = "policy_id")
private Policy policy;

您可以在主 table 上使用 AUTO-INCREMENT,这意味着您需要在 JPA/Hibernate.

中使用 IDENTITY 生成器

@MapsId 允许您与实体标识符 属性 共享相同的 SQL 列。它指示 Hibernate 使用此列来解析 @OneToOne@ManyToOne 关联。更改应始终通过 @Id 属性 传播,而不是对一侧(在 inserts/updates 期间被忽略)。