Hibernate inserts duplicates into @OneToMany collection

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

1
  • 27 Oct 2011, 10:22 AM

Activity

Show:

Kevin February 14, 2023 at 2:41 AM

I am using hibernate 5.6.7 and issue is still reproduciblesmiling face with tear

https://hibernate.atlassian.net/browse/HHH-16176

Guillaume Smet July 20, 2018 at 9:32 AM

This issue has already been fixed (no idea when). I added the provided test case to our test suite to prevent regressions.

Guillaume Smet July 18, 2018 at 10:05 AM

perfect, thanks.

I will add the test cases and close the issues later today.

Petar Tahchiev July 18, 2018 at 10:03 AM

Petar Tahchiev July 18, 2018 at 9:58 AM

I think what you are saying is correct, however, I don't want to take the responsibility of closing other people's tickets. Yes, to me it seems like they are fixed, however it would be great if you could add the provided test-cases to the master branch (I tested them and they are green) before closing the tickets. Both, this one and HHH7404 seems to me are OK.
I will create a new ticket now for my case.

Out of Date

Details

Assignee

Reporter

Labels

Affects versions

Priority

Created October 27, 2011 at 10:22 AM
Updated February 14, 2023 at 2:41 AM
Resolved July 20, 2018 at 9:33 AM

Flag notifications