Search code examples
hibernatejpamany-to-many

Hibernate many to many removing entries in join table while update owner table


I am trying to update an entity which is having many to many relationship with another table.

           @Entity(name = "coaching")
         public class CoachingEntity {


@ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.REFRESH })
    @JoinTable(name = "coaching_field", joinColumns = @JoinColumn(name = "coachingId",    referencedColumnName = "coachingId"), inverseJoinColumns = @JoinColumn(name = "fieldId", referencedColumnName = "fieldId"))
   private Set<FieldEntity> fieldEntityList;

Now, when I update CoachingEntity, hibernate is removing entries from coaching_field table (many to many join table). I have searched in internet (JPA update many-to-many deleting records) but I am not able to find the right approach. Even in JPA many to many merge on the owner triggers delete on join table, I tried his recommended approach where he used set but I am facing the same problem. As per https://stackoverflow.com/a/1078295/2116229, do I need to override equals and hashcode?


Solution

  • You need to overwrite equals() and hashCode() in your entities or you are going to run into issues sooner or latter, specially if your entities are part of a Set.

    See this for more details: https://community.jboss.org/wiki/EqualsAndHashCode

    If your problem persists after overwriting equals() and hashCode() and you are using a bidirectional relationship; then, you may need to add a mappedBy on the other side of the relationship and "link" both objects before persisting. Look at this answer for more details: Hibernate (4.1.2) and Spring (3.1.2) – ManyToMany relationship does not store records in JoinTable