Reputation: 219
I have three entities which look like this:
@Entity
class EntityA{
@OneToMany(cascade = javax.persistence.CascadeType.ALL, orphanRemoval = true)
private List<EntityB> _candidates = null;
}
@Entity
class EntityB{
@OneToOne
private EntityC _comp;
}
@Entity
class EntityC{
...
}
EntityB
has a property of type EntityC
. When an instance instanceC
of EntityC
is deleted, all the instances instancesB
of EntityB
referencing it must be deleted as well, from the instances of EntityA
containing the instancesB
.
Can I achieve this behavior through annotations? In the current state of the code, when deleting an EntityC
object I get the following exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails
Upvotes: 1
Views: 2257
Reputation: 21145
Your B table has foreign keys to both A and C with your current mappings which must be maintained. Because the fk to A is controlled by A's OneToMany to B, this one wont be too much of a problem as long as you remove A's reference to B when you delete B, just to keep your cached entities in sync the the changes. The relation to C on the other hand requires you to dereference C from B before it can be deleted, that or delete B as well- otherwise the fk in the B table will remain, violating the constraint. As the comments state, you will need some level of relationship management when removing entities.
Upvotes: 2