title: How can I cascade a JPA persist operation to a child entity when the parent has a generated identity?
body: <p>I have a bi-directional <code>@OneToOne</code> relationship between a parent entity and a child entity.</p>
  
  <p>In the parent, I have this (yes, the child is the owning side of the relationship):</p>
  
  <pre><code>@OneToOne(mappedBy = "parent", fetch = FetchType.EAGER, optional = true, cascade = { CascadeType.ALL })
  private Child child;
  </code></pre>
  
  <p>His primary key is (regrettably) generated by the database:</p>
  
  <pre><code>@Column(name = "id", updatable = false)
  @GeneratedValue(GenerationType.IDENTITY)
  @Id
  private long id;
  </code></pre>
  
  <p>In the child, I have this:</p>
  
  <pre><code>// note: insertable = false, updatable = false
  @JoinColumn(name = "parentId", referencedColumnName = "id", insertable = false, updatable = false)
  @OneToOne(optional = false, fetch = FetchType.EAGER, cascade = { CascadeType.REFRESH })
  private Parent parent;
  
  @Column(name = "parentId", updatable = false)
  @Id
  private long parentId;
  </code></pre>
  
  <p>Normally I would use a <code>@PrimaryKeyJoinColumn</code> annotation instead of these two mappings, but a couple of JPA providers have bugs in this area.</p>
  
  <p>At some point, I do some work on a new parent instance.  As part of that work I do this:</p>
  
  <pre><code>this.child = new Child(this);
  </code></pre>
  
  <p>...and inside the <code>Child(Parent)</code> constructor I do this:</p>
  
  <pre><code>this.parent = parent; // now the bidirectionality is complete
  if (parent != null) {
    this.parentId = parent.getId(); // suspect; will be 0L
  }
  </code></pre>
  
  <p>So if you're with me so far I have an object graph consisting of a <code>Parent</code> and a <code>Child</code> who have <code>@OneToOne</code> relationships with one another, properly initialized.  Both objects are unmanaged entities.</p>
  
  <p>Then I try to <code>persist()</code> the parent:</p>
  
  <pre><code>this.em.persist(parent);
  </code></pre>
  
  <p>...and I get a foreign key violation on our Informix database.  On the other hand, our H2 database processes this just fine.</p>
  
  <p>Is that what should be happening?  Am I doing something wrong?</p>