我不清楚JPA / Hibernate文档为什么在尝试添加子实体时必须设置对ManyToOne关系的父对象的引用。
例如,
如果我像这样进行两阶段添加:
第1阶段:
第二阶段:
child.setParentId(parent.getParentId())
而不是child.setParent(parent)
为什么即使在我保存的子实体上设置parentId时,我也会获得对父项的外键引用的Not Null Constraint违规?我希望能够自己管理孩子;他们的存在对父母没有影响。
我正在尝试做甚么可能吗?如果是这样,我需要将哪些秘密的注释混合在一起?
以下是一些概述我的问题的代码:
Parent.java
@Entity
@Table(name = "parents")
public class Parent
{
protected String parentId;
protected Collection<Child> children;
public Parent()
{
}
@Id
@Column(name = "parent_id", columnDefinition = "VARCHAR(42) NOT NULL", nullable = false, length = 42, insertable = true, updatable = false)
public String getParentId()
{
return parentId;
}
public void setParentId(String parentId)
{
this.parentId = parentId;
}
@OneToMany(mappedBy = "parent", cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
public Collection<Child> getChildren()
{
if(children == null){
children = new LinkedList<>();
}
return children;
}
public void setCards(Collection<Child> children)
{
this.children = children;
}
}
Child.java
@Entity
@Table(name="children")
public class Child
{
protected String childId;
protected Parent parent;
@Id
@Column(name="card_id", columnDefinition="VARCHAR(42) NOT NULL", length=42, nullable=false, insertable=true, updatable=false)
public String getCardId()
{
return childId;
}
public void setCardId(String childId)
{
this.childId = childId;
}
@JsonIgnore
@ManyToOne(fetch=FetchType.LAZY, cascade=CascadeType.ALL)
@JoinColumn(name="parent_id", nullable = false, updatable=false)
public Parent getCardholder()
{
return parent;
}
public void setParent(Parent parent)
{
this.parent = parent;
}
}