1

我的代码中有这样的父子关系(一对多/多对一)

父母

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

孩子没有从桌子上移开,有什么问题,你能帮我吗,对不起我的英语不好:-(

4

2 回答 2

3

child在这种情况下,不应从数据库中删除。如果这是您想要的行为,您需要启用“孤儿删除”:

@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval=true)
@LazyCollection (LazyCollectionOption.FALSE)
public List<Child> getChilds() {
    return childs;
}
于 2012-10-05T13:55:42.750 回答
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);
于 2013-03-22T10:11:42.400 回答