foreign key constraint in One To One relationship in JPA hibernate
<p>I have two entities <code>A</code> and <code>B</code> with one-to-one relationship. When I want to insert them into DB, I get the following error:</p>

<blockquote>
  <p>Cannot add or update a child row: a foreign key constraint fails
  (<code>mydb</code>.<code>a</code>, CONSTRAINT
  <code>FK_77pkrkrin5nqsx16b6nw6k9r7</code> FOREIGN KEY (<code>id</code>) REFERENCES
  <code>b</code> (<code>b_id</code>))</p>
</blockquote>

<pre><code>@JsonInclude(JsonInclude.Include.NON_NULL)     
@JsonIgnoreProperties(ignoreUnknown = true, value={"hibernateLazyInitializer", "handler"})
@Generated("org.jsonschema2pojo")
@Inheritance(strategy = InheritanceType.JOINED)
@Entity
public class A {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @JsonIgnore
  private Integer id;

  @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
  @PrimaryKeyJoinColumn(referencedColumnName="AId")
  @JsonIgnore
  private B b;

}

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true, value = {"hibernateLazyInitializer", "handler"})
@Generated("org.jsonschema2pojo")
@Entity
public class B {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private int bId;

  @OneToOne()
  @JsonIgnore
  private A a;

}
</code></pre>

<p>The insert operation will work perfectly if I remove the <code>optional=false</code>. I checked the objects before inserting them into DB and I make sure that <code>A</code> contains <code>B</code> and <code>B</code> contains <code>A</code>.</p>

<p>The SQL scripts for <code>A</code> and <code>B</code> creation are:</p>

<blockquote>
  <p>Hibernate: create table b (b_id integer not null auto_increment,
  string_results longtext, a_id integer, primary key (b_id))</p>
  
  <p>Hibernate: create table a (id integer not null auto_increment, primary
  key (id))</p>
  
  <p>Hibernate: alter table b add constraint FK_o3oen721etlltdc7ls82524nh
  foreign key (detail_id) references a (id)</p>
  
  <p>Hibernate: alter table a add constraint FK_77pkrkrin5nqsx16b6nw6k9r7
  foreign key (id) references b (b_id)</p>
</blockquote>