我的代码中的父和子之间有一个关系(一对多/多对一),如此
父母
@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;
}
}
和孩子
@JsonAutoDetect
@Entity
@Table(name="Child")
public class Child{
private Integer id;
private Parent parent;
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
@Column (name = "idchild")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.EAGER)
@NotFound(action = NotFoundAction.IGNORE)
@JoinColumn(name = "idparent")
@JsonIgnore
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent= parent;
}
}
一切都很好,但是当我做出像
这样的事情时parent.getChilds().remove(child);
session.update(parent);
孩子没有从桌子上移走,问题是什么,请你帮帮我吧,
抱歉我的英语不好: - (
答案 0 :(得分:3)
child
。如果这是您想要的行为,则需要启用“孤儿删除”:
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval=true)
@LazyCollection (LazyCollectionOption.FALSE)
public List<Child> getChilds() {
return childs;
}
答案 1 :(得分:0)
这可能会有所帮助
Child c = (Child) parent.getChilds();
parent.getChilds().remove(c);
c.setParent(null);
或
Child c = (Child) parent.getChilds();
parent.getChilds().remove(c);
session.delete(c);