从@OneToMany关系中删除子项

时间:2015-03-04 17:25:00

标签: java database hibernate one-to-many

在一对多关系中,如何删除子元素而不必查找和加载父元素,删除元素,更新父元素,然后删除子元素?为了进一步说明我的问题,我有两个类Foo(父母)和Don(Don的孩子):

@Entity
public class Foo {
    @Id
    @GeneratedValue
    private int id;

    @OneToMany
    private List<Don> dons;

    public int getId() {
        return id;
    }

    public List<Don> getDons() {
        // (loads dons as because lazy loading)
        return dons;
    }
}

@Entity
public class Don {
    @Id
    @GeneratedValue
    private int id;

    public int getId() {
        return id;
    }
}

如果我有一个Don实例,其中有几个Foos引用它,我会得到以下异常:

  

无法删除或更新父行:外键约束失败

我知道我可以从Foo中删除实例,但有没有办法在不找到Foos的情况下删除Don实例? (截至表演)

2 个答案:

答案 0 :(得分:1)

我认为您的情况应该是:删除Foos个实例,其中有几个Dons引用它

您可以添加cascade属性,然后当您删除Foos实例时,将自动删除关联的Dons实例,而不会给出外键错误:

@OneToMany(cascade = {CascadeType.ALL})
private List<Don> dons;

答案 1 :(得分:1)

this帖子所述,为了删除对象,需要双向绑定。添加从Don到Foo用@ManyToOne注释的引用,并将mappedBy =“parent”添加到Foo.dons解决了我的问题。最终代码:

@Entity
 public class Foo {
    @Id
    @GeneratedValue
    private int id;

    // Added mapped by, which refers to Don.parent
    @OneToMany(mappedBy = "parent")
    private List<Don> dons;

    public int getId() {
        return id;
    }

    public List<Don> getDons() {
        // (loads dons as because lazy loading)
        return dons;
    }
}

@Entity
public class Don {
    @Id
    @GeneratedValue
    private int id;

    // Added parent
    @ManyToOne
    private Foo parent;

    public int getId() {
        return id;
    }

    // Remember to set parent, otherwise we will loose the reference in the database.
    public void setParent(Foo parent) {
        this.parent = parent;
    }
}