Java JPA/Hibernate OnetoMany防止重复儿童

Java JPA/Hibernate OnetoMany防止重复儿童,java,hibernate,jpa,Java,Hibernate,Jpa,围绕这个主题有一些不同的问题已经有了答案,但从我所看到的很多答案都是旧的或者对我来说没有明确的意义 假设我有一个实体/表: @Entity @Table(name = "ParentTable") public class Parent { @Id @GeneratedValue private Integer id; @OneToMany(cascade = CascadeType.ALL) @NotNull private List<

围绕这个主题有一些不同的问题已经有了答案,但从我所看到的很多答案都是旧的或者对我来说没有明确的意义

假设我有一个
实体
/

@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

}
然后我通过以下方式构建了一些家长:

String childLabel = "child-label";
Parent a = new Parent(childLabel);
Parent b = new Parent(childLabel);
// Save both parents to a db 
它在表中创建两个具有不同ID的子实例。我理解这是因为正在创建
子对象的不同实例,然后分别保存


但我应该如何改变我的设计,以确保只保存和引用两个相同子对象的一个实例?我曾尝试构造孩子,然后将其交给父母,但随后出现主键错误

将构造函数改为子构造函数:

public Parent(Child childLabel){
    this.children = new ArrayList<>();
    this.children.add(childLabel);
}

如果有多个父级需要引用同一个子级,则可能需要使用多对多类型引用,而不是一对多类型引用。

更改构造函数以获取子级:

public Parent(Child childLabel){
    this.children = new ArrayList<>();
    this.children.add(childLabel);
}

如果多个家长需要引用同一个孩子,那么您可能需要使用多对多类型引用,而不是一对多类型引用。

非常感谢!我也不得不换成很多,但那是我的愚蠢,谢谢你!我也不得不换成很多,但那是我的愚蠢
@Column(unique=true, nullable=false)
private String label;