1

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)

Martin
  • 2,606
  • 4
  • 24
  • 38
  • hi, if i'm not mistake you want to delete only one of "Don" record right ? May i know you do found your solution ? I have the same problem as well.. wish you can share to me :) – Kim Aug 12 '16 at 09:26

2 Answers2

1

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;
Paul Lo
  • 6,032
  • 6
  • 31
  • 36
  • If that were the case, it would work. In my case however, I'm trying to delete don instances, not foos. – Martin Mar 04 '15 at 19:03
1

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;
    }
}
Community
  • 1
  • 1
Martin
  • 2,606
  • 4
  • 24
  • 38