If you are using it with Hibernate, you’ll have to explicitly define the annotation CascadeType.DELETE_ORPHAN
, which can be used in conjunction with JPA CascadeType.ALL
.
If you don’t plan to use Hibernate, you’ll have to explicitly first delete the child elements and then delete the main record to avoid any orphan records.
execution sequence
- fetch main row to be deleted
- fetch child elements
- delete all child elements
- delete main row
- close session
With JPA 2.0, you can now use the option orphanRemoval = true
@OneToMany(mappedBy="foo", orphanRemoval=true)