title: Why the Cascading persist does not work with many-to-many relationship in Hibernate?
body: <p>Please look at the following code snippets from 2 classes (Entities) <code>Student</code> and <code>Course</code></p>
  <pre class="lang-java prettyprint-override"><code>public class Student {
     ...
  
     @ManyToMany(cascade = CascadeType.ALL)
     @JoinTable(name = &quot;course_student&quot;,
          joinColumns = @JoinColumn(name=&quot;student_id&quot;),
          inverseJoinColumns = @JoinColumn(name=&quot;course_id&quot;)
     )
     private List&lt;Course&gt; courses;
     
     ...
  }
      
  public class Course {
     ...
     
     @ManyToMany(cascade = CascadeType.ALL)
     @JoinTable(name = &quot;course_student&quot;,
          joinColumns = @JoinColumn(name=&quot;course_id&quot;),
          inverseJoinColumns = @JoinColumn(name=&quot;student_id&quot;)
     )
     private List&lt;Student&gt; students;
     
     ...
  }
  </code></pre>
  <p>and the driver code is as follows</p>
  <pre class="lang-java prettyprint-override"><code>try {
      session.beginTransaction();
      Course course = new Course(&quot;Ukulele master class&quot;);
      Student student1 = new Student(&quot;Jishnu&quot;,&quot;M V&quot;,&quot;jishnumv@gmail.com&quot;);
      Student student2 = new Student(&quot;Praveen&quot;,&quot;M V&quot;,&quot;praveenmv@gmail.com&quot;);
      course.add(student1);
      course.add(student2);
      session.save(course);
      session.getTransaction().commit();
  } 
  </code></pre>
  <p>When I run this code I am getting the following exception</p>
  <pre><code>Exception in thread &quot;main&quot; java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.jithin.entity.Student
  </code></pre>
  <p>So my doubt is. <strong>persisting the Course does not persist the associated Student(s) even though we have mentioned CascadeType.ALL in the Course class. So why the cascading is not working in the case of many to many?</strong></p>
  <p>nb: When I saved both the student objects using <code>session.save()</code>, before saving the course object. There were no exception.</p>