We're updating the issue view to help you get more done. 

Hibernate inserts duplicates into @OneToMany collection

Description

Consider following entities (getters and setters 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") 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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 // 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.

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

Affects versions

5.2.2
3.6.7
5.0.7
4.0.0.CR4

Priority

Minor