JPA 2 orphanRemoval on OneToOne relation does not work properly

Description

I have an class A with a oneToRelation with a classe B :

@Entity
public class A{

@OneToOne(cascade = {CascadeType.ALL}, orphanRemoval=true)
B b;
...
}

If i do this :

A a = new A();

B b1 = new B();
a.setB(b1);
em.persist(a);

B b2 = new B();
a.setB(b2);
em.update(a);

As b1 become an orphan, Hibernate should remove it from the database. But it still remains in the DB.

Attachments

2
  • 28 Sep 2010, 11:15 AM
  • 20 Sep 2010, 04:43 PM

Activity

Show:

Brett MeyerMarch 7, 2014 at 5:31 PM

Bulk closing rejected tickets in "resolved" state.

EdmondoDecember 21, 2011 at 10:57 AM

As I am saying in HHH-4601, it exists a problem when the cascaded entity has auto-generated id.

What happens is that, when persisting or merging an entity with a @OneToOne to an entity with auto generated ID, the id is not updated in the object. Therefore, when you try to delete the parent entity, the child is not deleted correctly, because it is missing the id. If you replace your autogenerated ID in the child entity with a manual ID, all works fine.

Matt KirkAugust 25, 2011 at 12:37 PM

I've been hit by this today and will vote on it being fixed.

For those interested the work around we implemented was to change the mapping to OneToMany and manage the collection inside the entity such that clients only get a OneToOne view of the child record as follows:

@Entity
public class Child {

...
}

@Entity
public class Parent {

@OneToMany(..., orphanRemoval = true)
private Set<Child> children = new HashSet<Child>();

....

public Child getChild() {
if (children.size() == 1) {
return children.iterator().next();
}

return null;
}

public void doSomethingThatCreatesNewChild() {
if (getChild() != null) {
children.remove(getChild());
}

children.add(new Child());
}

}

This approach suits us better than having to make child entity table columns in the DB nullable and updating the same record each time.

Laura DeanAugust 22, 2011 at 8:52 PM

People who wanted to vote on this issue might want to vote on https://hibernate.atlassian.net/browse/HHH-6484#icft=HHH-6484 (Replacing an entity on a one-to-one delete-orphan association with a new instance does not delete the previous one).

Justin MaresMarch 9, 2011 at 6:37 PM

I would like to vote for this but this is no longer possible. Today I manually delete orphaned entity but I would like to have Hibernate transparently handling it.

Won't Fix
Created September 13, 2010 at 11:55 AM
Updated March 7, 2014 at 5:31 PM
Resolved September 27, 2010 at 5:25 PM

Flag notifications