有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java 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 我试着在一对多中添加以下内容:

cascade = CascadeType.ALL, orphanRemoval = true

它会给我这个错误

org.postgresql.util.PSQLException: ERROR: update or delete on table "parent" violates foreign key constraint "xxxxxxxxxxxxxxxxxxxxxxx" on table "child"

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

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) 个答案

  1. # 1 楼答案

    删除父项可能会失败,因为该父项还有其他子项。通常,为了删除某个孩子的父母,在这种情况下,您还需要删除该孩子的所有兄弟姐妹

    我对你的设计有点困惑,如果你真的想让一些父母和他们的孩子都失去兄弟姐妹,你应该这样做

    • 使父母/子女之间的所有相关关系具有双向性
    • 将父项删除也级联到子项

    例如,在child中:

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