【问题标题】:@OneToOne make primary key as foreign key at the same time (Spring JPA/Hibernate)@OneToOne 同时将主键作为外键(Spring JPA/Hibernate)
【发布时间】:2017-10-05 18:41:22
【问题描述】:

我有一个这样的实体:

@Entity
public class Person {

    @Id
    private Long id;

    private String firstName;

    // Getters and setters
}

id 不是自动生成的,而是由用户决定的。

我有第二个这样的实体:

@Entity
public class PersonDetail {

    @Id
    @OneToOne
    private Long id; // should be referred to id of Person entity
    // or maybe private Person person; ???

    private String language;
    private Integer age;

    // Getters and setters
}

同样在第二个实体中,id 不会自动生成。

我想建立一个@OneToOne 关系,我希望PersonDetailidPersonDetail 的主键,但同时它必须是@987654330 的外键@实体(id字段)。

Spring JPA / Hibernate 注解可以吗?

非常感谢, 安德烈亚

【问题讨论】:

标签: hibernate jpa spring-data-jpa one-to-one


【解决方案1】:

您可以关注此 wiki: Primary Keys through OneToOne and ManyToOne Relationships

将您的 PersonDetail 实体重写为:

@Entity
public class PersonDetail {

    @Id
    private Long id;

    @OneToOne
    @PrimaryKeyJoinColumn
    private Person person;

    private String language;
    private Integer age;

    // Getters and setters
}

【讨论】:

  • 为什么在PersonDetail 中引入单独的id 字段?
  • 因为任何实体都必须具有 Id 属性。
猜你喜欢
  • 2016-05-26
  • 1970-01-01
  • 1970-01-01
  • 2019-04-16
  • 2017-01-03
  • 2014-10-12
  • 2018-10-19
  • 2016-03-16
  • 1970-01-01
相关资源
最近更新 更多