Orphan removal in @OneToMany does not work properly (JPA 2.0)

Description

Consider following entities (getters, setters, equals and hashCode are omitted for brevity):

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 @Entity public class Parent { @Id @GeneratedValue private int id; @OneToMany(mappedBy="parent", orphanRemoval=true) private List<Child> children = new LinkedList<Child>(); } @Entity public class Child { @Id @GeneratedValue private int id; @ManyToOne private Parent parent; }

According to the specification of JPA 2.0 (section 11.1.36), removing a child entity from the parent's children collection should lead to it being removed from the database. However, following code leaves an orphaned child entity stored in the database:

1 2 3 4 5 6 7 8 // assuming there is one parent entity in the db // containing one child entity in its collection entityManager.getTransaction().begin(); Parent parent = entityManager.find(Parent.class, parentId); parent.getChildren().get(0).setParent(null); parent.getChildren().clear(); entityManager.getTransaction().commit();

Removing a parent entity however works fine (no orphans remain in the database).

I have attached a JUnit test case illustrating the behavior. I ran the test against another persistence provider, where the orphan was removed as expected.

I have also included the Hibernate-equivalent of the test (using Hibernate's native API instead of JPA). This code also cleans up the orphan as expected. Thus the bug seems to be related to the JPA implementation (EntityManager etc).

Environment

MySQL 5.1.54

Status

Assignee

Unassigned

Reporter

Damien

Fix versions

None

backPortable

None

Suitable for new contributors

None

Requires Release Note

None

Pull Request

None

backportDecision

None

Components

Affects versions

3.6.7
5.2.2

Priority

Major
Configure