title: JPA persists already persisted Objects from a ManyToMany relationship
body: <p>I have a @ManyToMany relationship between class A and class B : class A references a collection of class B instances, and this relationship is configured as CascadeType.ALL. So when a A is persisted with the entity manager, the B instances referenced by A are also persisted. </p>
  
  <p>Both A and B have an ID declared with the GenerationType.IDENTITY strategy to use the auto_inc from the MySQL database.</p>
  
  <p>The problem is :</p>
  
  <ol>
  <li>I create a new A</li>
  <li>I load some existing B objects from entityManager using JPQL</li>
  <li>I add the B objects to A's collection of Bs</li>
  </ol>
  
  <p>=> JPA tries to persist the B objects though they are already persisted (they just have been loaded).</p>
  
  <p>I don't understand why it tries to persist them again, they have been properly loaded, and their auto generated id has been well loaded as well.</p>
  
  <p>The ManyToMany declaration :</p>
  
  <pre><code>@ManyToMany(cascade={CascadeType.ALL})
  @JoinTable(name = "ENTRY_ENTITIES", joinColumns =
  @JoinColumn(name = "ENTRY", referencedColumnName = "ID"),
  inverseJoinColumns = @JoinColumn(name = "ENTITY", referencedColumnName = "ID"))
  private List&lt;Entity&gt; entities;
  </code></pre>
  
  <p>The Query to load existing objects from database :</p>
  
  <pre><code>T result = (T) entityManager.createQuery("SELECT x FROM " + entityName + " x WHERE x.externalId='" + externalId + "'").getSingleResult();
  </code></pre>
  
  <p>The persisting :</p>
  
  <pre><code>UserTransaction transaction = getTransaction();
  try {
      transaction.begin();
      entityManager.persist(entity);
      transaction.commit();
  } catch (Throwable t) {
      Logger.getLogger(JpaDao.class.getName()).log(Level.SEVERE, null, t);
  }
  </code></pre>
  
  <p>Thanks a lot for your help!</p>