Uploaded image for project: 'Hibernate ORM'
  1. HHH-6709

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

    Details

    • Bug Testcase Reminder (view):

      Bug reports should generally be accompanied by a test case!

    • Last commented by a user?:
      true
    • Sprint:

      Description

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

      @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:

      // 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).

        Attachments

          Issue links

            Activity

              People

              • Votes:
                9 Vote for this issue
                Watchers:
                15 Start watching this issue

                Dates

                • Created:
                  Updated: