首页 > 解决方案 > JPA/Hibernate OnetoMany 防止重复子代

问题描述

围绕这个主题有几个不同的问题已经有了答案,但据我所知,许多答案都是旧的,或者对我来说没有明确的意义。

假设我有一个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

}

然后Child作为:

@Entity
public class Child {

    @Id
    @GeneratedValue
    private Integer id;

    @NotNull
    private String label;

    public Child(String label){
         this.label = label;
    }

    // Get/Set/Constructors

}

然后我通过以下方式构建一些父母:

String childLabel = "child-label";
Parent a = new Parent(childLabel);
Parent b = new Parent(childLabel);
// Save both parents to a db 

它在表中创建两个具有不同 ID 的子实例。我知道这是因为Child正在创建不同的实例,然后分别保存。

但是我应该如何改变我的设计以确保只保存和引用两个相同孩子的一个实例?我尝试构建孩子然后给父母,但后来我得到一个主键错误。

标签: javahibernatejpa

解决方案


改变你的构造函数来取一个孩子:

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

如果要强制 Child 上的标签具有唯一性,请更改 Child 中的列定义

@Column(unique=true, nullable=false)
private String label;

如果多个 Parent 需要引用同一个孩子,那么您可能需要使用 ManyToMany 类型引用而不是 One to Many。


推荐阅读