@OneToOne 和 @JoinColumn 只保存 UUID 而不是整个对象

@OneToOne With @JoinColumn that holds only the UUID instead of the whole object

我正在使用 Java + Spring + Hibernate

测试以下代码时出现错误:

javax.persistence.PersistenceException: org.hibernate.PropertyAccessException: could not get a field value by reflection getter of com.XXX.XXX.entity.Policy.id

@Entity
@Table(name = "assignment")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Assignment extends BaseEntity {

    @Id
    @Column(name = "id")
    @Type(type = "pg-uuid")
    @NotTracked
    private UUID id;

    @OneToOne(targetEntity = Policy.class)
    @JoinColumn(name = "policy_id", nullable = false, referencedColumnName = "policy_id")
    @OnDelete(action = OnDeleteAction.CASCADE)
    @TrackedEntity(isIdentityField = true)
    private UUID policyID;
}

@Entity
@Table(name = "policy")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "policy")
@Inheritance(strategy = InheritanceType.JOINED)
public class Policy extends BaseEntity {

    @Id
    @Column(name = "policy_id")
    @Type(type = "pg-uuid")
    @NotTracked
    private UUID id;

    ...
    ...
    ..

}

当将 private UUID policyID;UUID 更改为 Policy 时,它工作得很好,有没有办法以某种方式设置对 Policy 中特定对象的引用作为 ID 而不是持有分配对象中的整个策略对象?

我认为没有理由使用 UUID 而不是对策略对象的引用。 你可以注释你想延迟加载对象,所以如果你想访问策略对象的另一个属性,它只会从数据库加载:

@OneToOne(targetEntity = Policy.class, fetch = FetchType.LAZY)

可以只包含 UUID,但它不再是休眠管理的 FK。我不建议这样做,因为您希望 Hibernate 管理您的 FK。您只需将 Assignment 更改为:

@Entity
@Table(name = "assignment")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Assignment extends BaseEntity {

    @Id
    @Column(name = "id")
    @Type(type = "pg-uuid")
    @NotTracked
    private UUID id;

    @Column(name="policy_id")
    private UUID policyID;
}

话虽如此,除非您手动将它们添加到数据库中,否则您将丢失所有针对该字段的级联选项和 FK 检查约束。