Hibernate jpa在从父集合中删除子集合时将其从表中删除并更新父集合
在我的代码中,父级和子级之间有这样一种关系(一对多/多对一) 父母Hibernate jpa在从父集合中删除子集合时将其从表中删除并更新父集合,hibernate,jpa,one-to-many,many-to-one,Hibernate,Jpa,One To Many,Many To One,在我的代码中,父级和子级之间有这样一种关系(一对多/多对一) 父母 @JsonAutoDetect @Entity @Table(name = "Parent") public class Parent{ private Integer id; private List<Child> childs; @Id @GeneratedValue(strategy= GenerationType.AUTO) @Column (name="idpar
@JsonAutoDetect
@Entity
@Table(name = "Parent")
public class Parent{
private Integer id;
private List<Child> childs;
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
@Column (name="idparent")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
@LazyCollection (LazyCollectionOption.FALSE)
public List<Child> getChilds() {
return childs;
}
public void setChilds(List<Child> childs) {
for (Child child: childs) {
child.setParent(this);
}
this.childs= childs;
}
}
一切都很好,但当我想
parent.getChilds().remove(child);
session.update(parent);
孩子还没从桌子上搬走,有什么问题,你能帮我一下吗?,
抱歉,我的英语不好:-(
在这种情况下,不应从数据库中删除子项
。如果这是您想要的行为,您需要启用“孤立项删除”:
@OneToMany(mappedBy=“parent”,cascade=CascadeType.ALL,orphanRemoving=true)
@LazyCollection(LazyCollectionOption.FALSE)
公共列表getChilds(){
返回儿童;
}
这可能会有帮助
Child c = (Child) parent.getChilds();
parent.getChilds().remove(c);
c.setParent(null);
或
我认为此解决方案用于在删除父项时删除所有子项,但我想从子项表中删除从prent集合中删除的子项;当我更新父项时。同样的问题,解决方案不起作用。我只想删除一个子项。父项和所有其他子项应保持存在。'remove(child)'不会从数据库中删除子项。在OnTo中,许多父项cascadeAll都是在删除父项以删除其所有子项的情况下定义的。工作正常,但不是这里的问题。您已经有一个可接受的答案,由Hibernate项目的主要开发人员之一给出……那么为什么要重新打开此问题?要从父项列表中删除子项与调用entityManager.remove()不同。因此,您的建议可能仅与OrphanRemove?一起使用?。
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval=true)
@LazyCollection (LazyCollectionOption.FALSE)
public List<Child> getChilds() {
return childs;
}
Child c = (Child) parent.getChilds();
parent.getChilds().remove(c);
c.setParent(null);
Child c = (Child) parent.getChilds();
parent.getChilds().remove(c);
session.delete(c);