JPA继承 - 不会删除子级

时间:2017-11-27 13:41:28

标签: java hibernate jpa

你可以帮助我删除继承记录。我正在使用实体管理器作为对象,当我调用em.remove(childInstance)时,仅删除子节点,并且父节点保持未删除状态。你能说出我做错了吗?

一般表格:

@MappedSuperclass
public abstract class General {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", columnDefinition = "serial")
    private Long id;

    // some other columns, getters and setters
}

父表:

@Entity
@Table(name = "PARENT_TABLE")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Parent extends General {

    // some columns and getters and setters
}

儿童班:

@Entity
@Table(name = "CHILD_TABLE")
@OnDelete(action = OnDeleteAction.CASCADE)
public class Child extends Parent {

@ManyToOne(fetch = FetchType.LAZY)
@OnDelete(action = OnDeleteAction.CASCADE)
@JoinColumn(name = "main_child",
        nullable = true,
        columnDefinition = "integer default 0")
private Child mainChild;

@OnDelete(action = OnDeleteAction.CASCADE)
@OneToMany(fetch = FetchType.LAZY, mappedBy = "child")
private Set<MyObjectA> objects = new HashSet<>();

    @OnDelete(action = OnDeleteAction.CASCADE)
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "id")
    private Set<Child> subChildren = new HashSet<>();

    // some columns and getters and setters
}

MyObjectA类:

@Entity
@Table(name = "object_a")
public class MyObjectA extends General {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "child_id", nullable = false)
    private Child child;
}

编辑:1 我忘了写其他实体引用子对象,而子对象引用它自己。

编辑:2 我尝试添加到One To Many:

cascade = CascadeType.ALL, orphanRemoval = true

并且它返回了我的错误

  

org.postgresql.util.PSQLException:错误:在表上更新或删除   &#34;父&#34;违反外键约束   &#34; xxxxxxxxxxxxxxxxxxxxxxx&#34;在桌子上&#34;孩子&#34;

我在数据库中查看该约束是什么,它引用该脚本:

ALTER TABLE public.child
  ADD CONSTRAINT xxxxxxxxxxxxxxxxxxxxxxx FOREIGN KEY (id)
      REFERENCES public.parent (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION; -- here should be ON DELETE CASCADE

1 个答案:

答案 0 :(得分:0)

删除父级可能会失败,因为该父级还有其他子级。一般来说,为了删除某个孩子的父母,你需要删除那个孩子的所有兄弟姐妹。

我对你的设计感到有点困惑 - 如果你真的打算将所有兄弟姐妹带给他们的孩子,你应该

  • 在父/子双向
  • 之间建立所有相关关系
  • 将父级删除也级联到子级

例如,在孩子的事情中:

@ManyToOne(cascade=CascadeType.REMOVE)
private Parent parent;

并在父母

@OneToMany(cascade=CascadeType.REMOVE, mappedBy="parent")
private Collection<Child> children;

你的情况中的儿童

@OneToMany(fetch = FetchType.LAZY, mappedBy = "id")
private Set<Child> subChildren = new HashSet<>();

应改为

// maps Child to itself bi-dir, note mappedBy changed form "id"
@OneToMany(fetch = FetchType.LAZY, mappedBy = "mainChild", 
              cascade=CascadeType.REMOVE) 
private Set<Child> subChildren = new HashSet<>();