title: Hibernate many to many association delete on update
body: <p>I'm working on a project where I have a Many to Many association in the next way:</p>
  
  <pre><code>public class Marca implements Serializable {
  
          @Id
          @GeneratedValue(strategy = GenerationType.IDENTITY)
          @Column(name = "id")
          private Long id;
  
          @Column(name = "nombre")
          private String nombre;
  
          @Column(name = "referencia")
          private Long referencia;
  
          @ManyToMany
          @JoinTable(name = "MarcaTipoEquipo", joinColumns = { @JoinColumn(name = "idMarca") }, inverseJoinColumns = { @JoinColumn(name = "idTipoEquipo") })
          private Set&lt;TipoEquipo&gt; equipos;
  }
  
  public class TipoEquipo implements Serializable {
      @ManyToMany(mappedBy = "equipos")
      private Set&lt;Marca&gt; marcas;
  
  }
  </code></pre>
  
  <p>When I update a Marca object, the records in the join table are deleted where id equals Marca object id.</p>
  
  <p>I've tried adding equals and hashcode methods on the TipoEquipo class as this post <a href="https://stackoverflow.com/questions/4063648/why-is-hibernate-deleting-rows-from-join-table-when-adding-element-to-set-mappin">Why is hibernate deleting rows from join table when adding element to set mapping many-to-many?</a> recommends: </p>
  
  <pre><code>@Override
  public boolean equals(Object obj) {
      return ((TipoEquipo) obj).getNombre().equalsIgnoreCase(this.nombre);
  }
  
  @Override
  public int hashCode() {
      return super.hashCode();
  }
  </code></pre>
  
  <p>What am I doing wrong? How can avoid Hibernate deletes the join table records?</p>
  
  <p>EDIT:</p>
  
  <p>Code to store the data</p>
  
  <pre><code>public synchronized Marca actualizar(Marca entity) {
      Long id = entity.getId();
      entity.setId(null);
  
      Marca marcaAnterior = busquedaGenericaBs.buscarPorId(Marca.class, id);
  
      marcaAnterior.setIdEstatus(ClaveEstatus.POR_VALIDAR_MODIFICACION
              .getClave());
  
      entity.setIdEstatus(ClaveEstatus.POR_VALIDAR_MODIFICACION_NUEVO
              .getClave());
  
      entity.setReferencia(id);
  
      genericDao.save(entity);
  
      return genericDao.update(marcaAnterior);
  }
  </code></pre>