简体   繁体   中英

Delete a child from a @OneToMany relationship

In a One-To-Many relationship, how can I delete a child element without having to find and load up the parent, removing the element, update parent, THEN delete the child? To further illustrate my problem, I have the two classes Foo (parent) and Don (child of 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;
    }
}

If I have a Don instance with several Foos referring to it, I would get the following exception:

Cannot delete or update a parent row: a foreign key constraint fails

I know I can remove the instance from Foo, but is there a way to remove Don instances without finding Foos? (as of performance)

I think your situation should be: delete a Foos instance with several Dons referring to it

You can add cascade attribute, then when you delete a Foos instance, the associated Dons instances would be deleted automatically without giving foreignkey error:

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

As stated in this post, a bidirectional binding is required in order to delete the object. Adding a reference from Don to Foo annotated with @ManyToOne, and added mappedBy="parent" to Foo.dons solved my issue. The final code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM