title: Hibernate / Spring Data JPA sporadically fails when trying to persist parent with nested object
body: <p>I want to have a unidirectional one to many relationship between my tables Employee and Phone currently defined as:</p>
  <pre><code>@Entity
  public class Employee {
    @Id
    private String id;
    ...
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
    @JoinColumn(name=&quot;FK_EMP_ID&quot;, nullable = false)
    private List&lt;Phone&gt; phones;
    ...
  }
  
  @Entity
  public class Phone {
    @Id
    private String id;
    
    private long phoneNumber;
  }
  </code></pre>
  <p>Only the Employee object has its repository class (Spring Data JPA) so the only way to insert, update, delete phone numbers is through its parent as desired. Ids are also UUID generated in the constructor of our entities.</p>
  <p>On top of that, we have configured Hibernate/JPA to batch SQL statements and order both insert and update as follow:</p>
  <pre><code>jpaProperties.setProperty(&quot;hibernate.jdbc.batch_size&quot;, &quot;1000&quot;);
  jpaProperties.setProperty(&quot;hibernate.order_inserts&quot;, &quot;true&quot;);
  jpaProperties.setProperty(&quot;hibernate.order_updates&quot;, &quot;true&quot;);
  jpaProperties.setProperty(&quot;hibernate.batch_versioned_data&quot;, &quot;true&quot;);
  </code></pre>
  <p>The issue is, some very few times, we see the following exception:</p>
  <blockquote>
  <p>&quot;HHH000315: Exception executing batch [java.sql.BatchUpdateException: Batch entry 1 insert into Phone (phone_number, FK_EMP_ID, id) values ('1234567890'::numeric, 'fdcf4003-4d39-4dbb-b8a3-cc7d41b67652', 'bb3816b7-266d-4c07-8c34-71598e862505') was aborted: ERROR: insert or update on table &quot;Phone&quot; violates foreign key constraint &quot;FKoaw1635nkk2ub4i3nf8d8441e&quot;\n  Detail: Key (FK_EMP_ID)=(fdcf4003-4d39-4dbb-b8a3-cc7d41b67652) is not present in table &quot;Employee&quot;.  Call getNextException to see other errors in the batch.], SQL: insert into Phone (hone_number, FK_EMP_ID, id) values (?, ?, ?, ?)&quot;</p>
  </blockquote>
  <p>How do I fix my stuff to prevent Hibernate/JPA saving the child object before the parent object as it will obviously fail ?
  Again, this exception occurs sporadically only when batching on a total of 80k entities.</p>
  <p>Thank you</p>
  <p>Lib versions =&gt; Hibernate: 5.4.28.Final &amp; Spring Data JPA: 2.3.7.RELEASE</p>