围绕这个主题有几个不同的问题已经有了答案,但据我所知,许多答案已经过时或对我来说没有明确的意义。
假设我有一个Entity
/Table
:
@Entity
@Table(name = "ParentTable")
public class Parent {
@Id
@GeneratedValue
private Integer id;
@OneToMany(cascade = CascadeType.ALL)
@NotNull
private List<Child> children;
public Parent(String childLabel){
this.children = new ArrayList<>();
this.children.add(new Child(childLabel));
}
// Get/Set/Constructors
}
然后子
为:
@Entity
public class Child {
@Id
@GeneratedValue
private Integer id;
@NotNull
private String label;
public Child(String label){
this.label = label;
}
// Get/Set/Constructors
}
然后我通过以下方式构建一些 parent :
String childLabel = "child-label";
Parent a = new Parent(childLabel);
Parent b = new Parent(childLabel);
// Save both parents to a db
它在表中创建两个具有不同 ID 的子实例。据我所知,这是因为 Child
的不同实例被创建然后单独保存。
但是我应该如何更改我的设计以确保仅保存和引用两个相同子项的一个实例?我尝试过构建 child 然后交给 parent ,但后来我得到了主键错误。
最佳答案
更改您的构造函数以采用子代:
public Parent(Child childLabel){
this.children = new ArrayList<>();
this.children.add(childLabel);
}
如果您想强制 Child 上标签的唯一性,请更改 Child 中的列定义
@Column(unique=true, nullable=false)
private String label;
如果多个父级需要引用同一个子级,那么您可能需要使用 ManyToMany 类型引用而不是一对多。
关于java - JPA/Hibernate OnetoMany 防止重复子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55518446/