java - 删除并保存 Child : JPA

标签 java jpa

这是我的实体:

@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;

  ...
}

我想执行以下操作:

  1. 从父项(而不是父项本身)中删除子实体。
  2. 将新的子实体添加到父实体 (parent.setChild(child))。
  3. 现在将子实体保存到数据库中并相应地更新父实体。

这是我尝试过的方法,但它为父级引发了 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/

相关文章:

java - 如何使用 JodaTime 保留原始时区

Java 结果集到 EJB

java - JPA 标准在所选日期上添加一天

java - 在纯 JPA @Query 中传递 Enum 值有哪些方法?

java - 我们如何合并不同外观和感觉的元素?

java - Selenium switchTo 返回错误 org.openqa.selenium.WebDriverException : unknown error: cannot determine loading status

hibernate - 如何将 Hibernate 从 4.3 升级到 5.2 以迁移到 JDK 10?

java - 使用 EclipseLink 自定义 JPA 字段名称映射

java - 转移到 OpenJDK-11 但在 Java 8 中编译

java - 访问 JPA 实体中的父实体