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.

Environment

Hibernate 2.5 (tested with 3.5.4)

Activity

Show:
Justin Mares
March 9, 2011, 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.

Laura Dean
August 22, 2011, 8:52 PM

People who wanted to vote on this issue might want to vote on (Replacing an entity on a one-to-one delete-orphan association with a new instance does not delete the previous one).

Matt Kirk
August 25, 2011, 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.

Edmondo Porcu
December 21, 2011, 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.

Brett Meyer
March 7, 2014, 5:31 PM

Bulk closing rejected tickets in "resolved" state.

Assignee

Emmanuel Bernard

Reporter

Loïc D

Fix versions

None

Labels

None

backPortable

None

Suitable for new contributors

None

Requires Release Note

Affirmative

Pull Request

None

backportDecision

None

Priority

Major
Configure