java.lang.IllegalStateException: Multiple representations of the same entity with @ManyToMany 3 entities

情到浓时终转凉″ 提交于 2019-11-26 22:39:16

Fixed it by removing CascadeType.MERGE on Permission entity

The correct solution would have been to upgrade to hibernate 4.2.15 / 4.3.6 or above and add the following lines to your persistence.xml:

<property name="hibernate.event.merge.entity_copy_observer" value="allow"/>

Check your equals and hashCode method, ensure that it is consistent and correctly defined. For example I had copied and mistakenly pasted another-class when computing hashCode, this caused the object never to be equal with itself :(.

I ran into the same problem too and solved it by add a few configs in application.yaml files.

  jpa:
    properties:
      hibernate:
        enable_lazy_load_no_trans: true
        event:
          merge:
            entity_copy_observer: allow

See it here How to persist a new entity containing multiple identical instances of another unpersisted entity with spring-boot and JPA?

In my case, moving the fetch operation and save operation in same @Transactional block solved the problem.

error occurs when we have multiple object of same time in HashSet.Possible due to incorrect hash function.Hashset check equality of object on the basis of hash function between two objects.

Way to debug

Just try to print hashset you will see multiple object of same type.

Solution::#

  • Use HashSet while defining one to many relationships.
  • Avoid using Lists.
  • Make sure your hash function should be correct.

@LazyCollection(LazyCollectionOption.FALSE

@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)

@JoinColumn(name = "translate_id")

I could fix it by replacing

cascade = CascadeType.All

with

casecade={CascadeType.PERSIST,CascadeType.REMOVE}

For Hibernate see the workaround here HHH-9106.

Beagle

Just a note to say I am using Hibernate Core 4.3.8 in a Spring MVC application, based on Spring Core 4.1.6. The workaround:

<property name="hibernate.event.merge.entity_copy_observer" value="allow"/>

Did not work for me. I needed to remove the CascadeType.MERGE in order to correctly populate an @ManyToMany. Not sure if newer versions of Hibernate have fixed this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!