JPA CascadeType.ALL does not delete orphans

Paul Whelan picture Paul Whelan · Nov 20, 2008 · Viewed 173k times · Source

I am having trouble deleting orphan nodes using JPA with the following mapping

@OneToMany (cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "owner")
private List<Bikes> bikes;

I am having the issue of the orphaned roles hanging around the database.

I can use the annotation org.hibernate.annotations.Cascade Hibernate specific tag but obviously I don't want to tie my solution into a Hibernate implementation.

EDIT: It seems JPA 2.0 will include support for this.

Answer

Varun Mehta picture Varun Mehta · Nov 20, 2008

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

  1. fetch main row to be deleted
  2. fetch child elements
  3. delete all child elements
  4. delete main row
  5. close session

With JPA 2.0, you can now use the option orphanRemoval = true

@OneToMany(mappedBy="foo", orphanRemoval=true)