views:

13058

answers:

5

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 @org.hibernate.annotations.Cascade Hibernate specific tag but obviously I don't want to tie my solution into a hibernate implementation.

Any pointers greatly appreciated.

EDIT: It seems JPA 2.0 will include support for this, which I am very happy about.

+3  A: 

According to Java Persistence with Hibernate, cascade orphan delete is not available as a JPA annotation.

It is also not supported in JPA XML.

toolkit
+10  A: 

If you are using it with Hibernate, you'll have to explicitly define org.hibernate.annotations.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
Varun Mehta
thanks I ended up going this route, I think this is a bit of an oversite for the JPA spec.
Paul Whelan
The JPA 2.0 standard now has deleteOrphan as an attribute to @OneToManyIf you are using the latest hibernate you can do @OneToMany(..., deleteOrphan=true)
jomohke
+2  A: 

If you are using JPA with EclipseLink, you'll have to set the @PrivateOwned annotation.

Documentation: Eclipse Wiki - Using EclipseLink JPA Extensions - Chapter 1.4 How to Use the @PrivateOwned Annotation

Daniel Murygin
+7  A: 

If you are using JPA 2.0, you can now use the orphanRemoval=true attribute of the @xxxToMany annotation to remove orphans.

Actaully, org.hibernate.annotations.CascadeType.DELETE_ORPHAN has been deprecated in 3.5.2-Final.

Kango_V
+1 for providing the uptodate answer to this question!
Nils Schmidt
Actually I think orphanRemoval=true means something else, i.e., delete an object when I remove it from it's parent's collection. See http://download.oracle.com/javaee/6/tutorial/doc/bnbqa.html#giqxy
Archie
A: 

I just find this solution but in my case it doesn't work :

OneToMany(cascade = CascadeType.ALL, targetEntity = MyClass.class, mappedBy = "xxx", fetch = FetchType.LAZY, orphanRemoval = true)

Valéry Stroeder