title: JPA - ManyToMany Cascading behavior
body: <p>I have a simple  manyToMany relationship between <strong>Students</strong> and <strong>Classes</strong>.</p>
  <p><strong>Tables:</strong></p>
  <ul>
  <li>student</li>
  <li>student_classe (JOIN TABLE)</li>
  <li>classe</li>
  </ul>
  <p>Querying data is working flawless, but saving is not getting the relation between student and classes saved into student_classe table, or, when I use <strong>CASCADE = ALL</strong> in the Student OneToMany relation, it throws an exception:</p>
  <pre><code>(org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint &quot;classe_pkey&quot;):
  </code></pre>
  <p>I thought using CascadeType.DETACH in the ManyToOnes relationships in the JOIN TABLE would avoid that to happen. What Am I missing here?</p>
  <pre><code>@Table(name = &quot;student&quot;)
  @Entity
  class Student {
  
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @Column(name = &quot;id&quot;, nullable = false)
      private Long id;
  
      @Column(name = &quot;name&quot;, nullable = false, length = 100)
      private String name;
  
      @OneToMany(mappedBy = &quot;student&quot;)
      private Set&lt;StudentClasse&gt; studentClasses;
  
     // ...
  }
  
  @Embeddable
  public class StudentClasseId implements Serializable {
  
      private static final long serialVersionUID = -8635992607670843018L;
  
      @Column(name = &quot;student_id&quot;, nullable = false)
      private Long studentId;
  
      @Column(name = &quot;classe_id&quot;, nullable = false)
      private Long classeId;
  
     // ...
  }
  
  @Table(name = &quot;student_classe&quot;)
  @Entity
  class StudentClasse {
  
      @EmbeddedId
      private StudentClasseId id;
  
      @ManyToOne(cascade = CascadeType.DETACH)
      @MapsId(&quot;studentId&quot;)
      @JoinColumn(name = &quot;student_id&quot;)        
      private Student student;
  
      @ManyToOne(cascade = CascadeType.DETACH)
      @MapsId(&quot;classeId&quot;)
      @JoinColumn(name = &quot;classe_id&quot;)        
      private Classe classe;
      
      // ...
  }
  
  @Table(name = &quot;classe&quot;)
  @Entity
  class Classe {
  
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @Column(name = &quot;id&quot;, nullable = false)
      private Long id;
  
      @Column(name = &quot;name&quot;, nullable = false, length = 100)
      private String name;
  
      @OneToMany(mappedBy = &quot;classe&quot;)
      private Set&lt;StudentClasse&gt; studentClasses;
  
     // ...
  }
  </code></pre>