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

Hibernate inserts duplicates into @OneToMany collection

    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 and setters are omitted for brevity):

      @Entity
      public class Parent
      {
      	@Id
      	@GeneratedValue
      	private int id;
      
      	@OneToMany(mappedBy="parent")
      	private List<Child> children = new LinkedList<Child>();
      }
      
      @Entity
      public class Child
      {
      	@Id
      	@GeneratedValue
      	private int id;
      
      	@ManyToOne
      	private Parent parent;
      }
      

      Now consider following code snippet, which persists one parent and one child entity and then prints the children of the parent.

      // persist parent entity in a transaction
      
      EntityManager em = emf.createEntityManager();
      em.getTransaction().begin();
      
      Parent parent = new Parent();
      em.persist(parent);
      int id = parent.getId();
      
      em.getTransaction().commit();
      em.close();
      
      // relate and persist child entity in a new transaction
      
      em = emf.createEntityManager();
      em.getTransaction().begin();
      
      parent = em.find(Parent.class, id);
      // *: parent.getChildren().size();
      Child child = new Child();
      child.setParent(parent);
      parent.getChildren().add(child);
      em.persist(child);
      
      System.out.println(parent.getChildren()); // -> [Child@36bf7916, Child@36bf7916]
      
      em.getTransaction().commit();
      em.close();
      

      The child entity is wrongly being inserted twice into the list of children of the parent entity.

      When doing one of the following, the code works fine (no duplicate entries in the list):

      • remove the mappedBy attribute in the parent entity
      • perform some read operation on the list of children (e.g. uncomment line marked by *)

      Also, when testing against another persistence provider, the code works as expected (no duplicates).

      Take a look at axtavt's answer to my post on Stack Overflow. He seems to know why this problem occurrs.

      I have attached a simple JUnit test for this issue.

        Attachments

          Issue links

            Activity

              People

              • Votes:
                27 Vote for this issue
                Watchers:
                31 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved: