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 楼答案
删除父项可能会失败,因为该父项还有其他子项。通常,为了删除某个孩子的父母,在这种情况下,您还需要删除该孩子的所有兄弟姐妹
我对你的设计有点困惑,如果你真的想让一些父母和他们的孩子都失去兄弟姐妹,你应该这样做
例如,在child中:
在父母身上
在你的案例中在儿童中
应该改成