【发布时间】:2021-02-08 13:29:29
【问题描述】:
我在父实体和子实体之间有@OneToMany 和@ManyToOne 关系。
@Entity
@Table(name = "parent")
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@OneToMany(targetEntity=Measurement.class, mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
@JsonManagedReference
private List<Child> children = new ArrayList<>();
}
我有这样的子实体
@Entity
@Table(name = "child")
public class Child {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne(targetEntity=Parent.class, fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
@JsonBackReference
private Parent parent;
保存此数据后,数据库如下所示,
Parent:
id
1
Child
id parent_id
2 1
我的问题是,为什么孩子的主键是 2 而不是 1?在子表中,它可以有一个主键为 1,外键引用父级为 1。当我再添加一个父表时,表看起来像这样,
Parent:
id
1
3
Child
id parent_id
2 1
4 3
我做错了什么还是预期的行为?
【问题讨论】:
-
从
Parent.children中删除@PrimaryKeyJoinColumn注释。
标签: sql spring-boot hibernate jpa spring-data-jpa