Reputation: 2785
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)
Upvotes: 1
Views: 1481
Reputation: 2785
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;
}
}
Upvotes: 1
Reputation: 6138
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;
Upvotes: 1