[hibernate-issues] [Hibernate-JIRA] Created: (HHH-6776) Hibernate inserts duplicates into @OneToMany collection

Damien (JIRA) noreply at atlassian.com
Thu Oct 27 04:24:21 EDT 2011


Hibernate inserts duplicates into @OneToMany collection
-------------------------------------------------------

                 Key: HHH-6776
                 URL: http://opensource.atlassian.com/projects/hibernate/browse/HHH-6776
             Project: Hibernate Core
          Issue Type: Bug
    Affects Versions: 4.0.0.CR4, 3.6.7
         Environment: MySQL 5.1.54
            Reporter: Damien
            Priority: Minor
         Attachments: Test.zip

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

{code:java}
@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;
}
{code}

Now consider following code snippet, which persists one parent and one child entity and then prints the children of the parent.
{code:java}
// 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 at 36bf7916, Child at 36bf7916]

em.getTransaction().commit();
em.close();
{code}

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|http://stackoverflow.com/questions/7903800/hibernate-inserts-duplicates-into-a-onetomany-collection/7905027#7905027] to my post on Stack Overflow. He seems to know why this problem occurrs.

I have attached a simple JUnit test for this issue.

--
This message is automatically generated by JIRA.
For more information on JIRA, see: http://www.atlassian.com/software/jira

        


More information about the hibernate-issues mailing list