title: Spring-Data JPA: EntityExistsException: A different object with the same identifier value
body: <p>I have an issue, what I am close to solution or better said I come closer how to avoid the issue <code>EntityExistsException: A different object with the same identifier value</code> BUT without understanding what is really the problem. To keep code short and concentrated I did a small application to simulate the problem in my project.</p>
  
  <p>First I have a CrudRepository what stays always the same:</p>
  
  <pre><code>public interface EntityARepository extends CrudRepository&lt;EntityA, Long&gt; {}
  </code></pre>
  
  <p>First I have to entities, one of them has a relation to the other:</p>
  
  <pre><code>@Entity
  @EqualsAndHashCode(of={"name"})
  @ToString(of={"name"})
  @XmlRootElement
  public class EntityA {
  
      @Id
      @GeneratedValue
      @Setter
      private Long id;
  
      @Setter
      @Column(nullable=false, unique=true)
      private String name;
  
      @Setter
      @ManyToOne(fetch=EAGER, cascade={PERSIST, MERGE})
      private EntityB entityB;
  
  }
  
  @ToString(of = { "name" })
  @EqualsAndHashCode(of = { "name" })
  @Entity
  class EntityB {
      @Id
      // @GeneratedValue =&gt; produces issue!
      @Setter
      private Long id;
  
      @Setter
      @XmlAttribute
      @Column(nullable=false, unique=true)
      private String name;
  }
  </code></pre>
  
  <p>Then I generate data and try to save them:</p>
  
  <pre><code>@Component
  public class DatabaseInitializer implements InitializingBean {
      @Autowired EntityARepository repository;
  
      @Override
      public void afterPropertiesSet() throws Exception {
          final Set&lt;EntityA&gt; aEntities = createAEntities();
          repository.save(aEntities);
      }
  
      private  Set&lt;EntityA&gt; createAEntities() throws Exception {
          Set&lt;EntityA&gt; aEntities = new HashSet&lt;&gt;();
          aEntities.add(getFirstEntityA());
          aEntities.add(getSecondEntityA());
          return aEntities;
      }
  
      private EntityA getFirstEntityA(){
          EntityA a = new EntityA();
          // a.setId(1L);
          a.setName("a-1");
          a.setEntityB(getFirstEntityB());
          return a;
      }   
  
      private EntityA getSecondEntityA(){
          EntityA a = new EntityA();
          // a.setId(2L);
          a.setName("a-2");
          a.setEntityB(getFirstEntityB());
          return a;
      }
  
      private EntityB getFirstEntityB() {
          EntityB b = new EntityB();
          b.setId(1l);
          b.setName("b-1");
          return b;
      }
  }
  </code></pre>
  
  <p>With this constallation I become a <code>EntityExistsException</code>:</p>
  
  <pre><code>Caused by: javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [com.example.EntityB#1]
  </code></pre>