Wednesday, May 6, 2009

JPA does not delete orphans

Don't really understand way, but there seems to be a limitation in the framework that does not permit this. If you search the net you'll find many frustrated programmers because of this.

There are some solutions. These solutions imply that the foreign key in the child table allows null. Without this, we can not obtain orphans (a row in the child table which has the foreign key to the parent set on null), and you will get an exception before having the "not deleted orphans" problem. If you need that constraint: foreign key in child must not allow null, there may be another solution which I hope to make time and test so I can post it here soon.

1. If you use a Hibernate implementation behind JPA, you can use the Hibernate annotation @Cascade(CascadeType.DELETE_ORPHAN) .

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

@OneToMany
@Cascade(CascadeType.DELETE_ORPHAN)
private List childList;

<dependency>
<groupid>org.hibernate</groupid>
<artifactid>hibernate-annotations</artifactid>
<version>3.4.0.GA</version>
</dependency>

2. Manually delete the orpnas after each update that denerate orphans.

entityManager.merge(parentEntity);
em.flush();

//delete orphans
em.createQuery(
"DELETE ChildEntity child WHERE child.parentEntity IS NULL").executeUpdate();

Well, that's life, you got to be a killer from time to time... poor orphans

If you have questions, just ask.

No comments:

Post a Comment