title: JPA insert parent/child results in MySQLIntegrityConstraintViolationException
body: <p>This has already been asked a number of times, but I don't find any good answers so I'll ask it again.</p>
  
  <p>I have parent-children unidirectional relation as follows:</p>
  
  <pre><code>@Entity
  @Table(name = "PARENT")
  public class Parent {
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @Column(name = "ID")
      private Long parentId;
  
      @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
      @JoinTable(name = "CHILD", joinColumns = @JoinColumn(name = "parent_id"), inverseJoinColumns = @JoinColumn(name = "ID"))
      private List&lt;Child&gt; children;
  }
  
  @Entity
  @Table(name = "CHILD")
  public class Child {
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @Column(name = "ID")
      private Long id;
  
      @Column(name = "PARENT_ID")
      private Long parentId;
  
      //some other field
  }
  </code></pre>
  
  <p>I create an instance of the parent, assign a list of children to it and try to persist it:</p>
  
  <pre><code>Parent p = new Parent();
  List&lt;Child&gt; children = new ArrayList&lt;Child&gt;();
  Child c = new Child();
  children.add(c);
  p.addChildren(children);
  em.merge(p);
  </code></pre>
  
  <p>When the code runs, I get the following exception:</p>
  
  <blockquote>
    <p>MySQLIntegrityConstraintViolationException: Cannot add or update a
    child row: a foreign key constraint fails
    (<code>testdb</code>.<code>child</code>, CONSTRAINT <code>parent_fk</code>
    FOREIGN KEY (<code>parent_id</code>) REFERENCES <code>parent</code> (<code>id</code>) ON
    DELETE NO ACTION ON UPDATE NO ACTION)</p>
  </blockquote>
  
  <p>I'm assuming this is due to the fact that the parent is not fully inserted when the child is being attempted to be inserted.</p>
  
  <p>If I don't add the children to the parent, the parent gets inserted just fine.
  I tried switching the GeneratedValue generation strategy but that did not help.</p>
  
  <p>Any ideas how to insert the parent &amp; the children at the same time?</p>
  
  <p><strong>Edit:</strong> Even if I persist the parent first, I'm still getting the same error. I determined it's because the parent_id is not set in the child; the child is default constructed and thus the parent_id is set to 0 which does not exist thus the foreign key constraint validation.</p>
  
  <p>Is there a way to get jpa to automatically set the parent_id of the children that are assigned to the parent instance?</p>