这是我的实体:
@Entity
public class Parent {
@Id
@Column(name = "ID")
private Long id;
@OneToMany(cascade = {CascadeType.ALL}, mappedBy = "parent")
private Set<Child> childs = new HashSet<Child>();
...
}
The child:
@Entity
public class Child {
@Id
@Column(name = "ID")
private Long id;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="PARENTID", nullable = false)
private Parent parent;
...
}
我想执行以下操作:
- 从父项(而不是父项本身)中删除子实体。
- 将新的子实体添加到父实体 (
parent.setChild(child)
)。 - 现在将子实体保存到数据库中并相应地更新父实体。
这是我尝试过的方法,但它为父级引发了 ConstraintViolationexception
:
entityManager.remove(parent.getChild())
parent.setChild(new Child())
entityManager.merge(parent);
我该如何解决这个问题?
最佳答案
“旧”子项可能仍然引用父项,而新子项则没有。两者都是一个问题。
除了删除旧的子实例之外,您还应该将子实例的 parent
引用设置为 null
。
除了将新的子项添加到父项之外,您还需要将父项添加到子项以提供外键。
不要从多边(子)级联到一侧(父)。这种级联的行为是未定义的,可能会以意想不到的方式工作。
编辑:JPA 2.0 规范的内容:
Note that it is the application that bears responsibility for maintaining the consistency of runtime relationships—for example, for insuring that the “one” and the “many” sides of a bidirectional relationship are consistent with one another when the application updates the relationship at runtime.
关于java - 删除并保存 Child : JPA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24280097/