Duplicate child inserts during merge operation in hibernate

Parent entity has list of child object marked as “LAZY” with CascadeType.ALL. When I tried to add child into parent and merge it, it tries to inserts two child records.

This issue can be fixed in following ways

Solution 1:

    Retrieve the child list size() to initialize lazy child collections, add the new child and merge it.

It will insert one child record only. Ensure that it is bounded in a transaction.

parent.getChilds().size();

    parent.getChilds().add(child);

    entityManager.merge(parent);

 

Solution 2:

    Simply add the new child into parent and don’t call merge operation. Ensure that it is bounded in a transaction.

    

parent.getChilds().add(child);

Pick up any solution that works out for you.

This is a bug in Hibernate marked as closed but not fixed https://hibernate.onjira.com/browse/HHH-3332.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: