title: JPA Hibernate. Persist parent and children entities with foreign key reference to a parent in one call
body: <p>I have the following problem: Having a class A</p>
  
  <pre><code> Class A {
        ...
  
        @Id
        @GeneratedValue( strategy = GenerationType.IDENTITY )
        @JsonIgnore
        private Long id;
  
        @OneToMany(cascade=CascadeType.PERSIST, orphanRemoval = true, fetch = FetchType.EAGER)
        @JsonView(View.Extended.class )
        @JoinColumn(name="b_fkey", referencedColumnName = "id")
        List&lt;B&gt; b;
        ...
   }
  </code></pre>
  
  <p>and class B: </p>
  
  <pre><code> Class B {
        ...
        private Long b_fkey;
        ...
   }
  </code></pre>
  
  <p>I am trying to persist it as follows:</p>
  
  <pre><code> ...
   A a = new A();
   a.setStuff();
   A aa = aDao.save(a);
   // no list of B's
  
   for(B b : List&lt;B&gt;) {
       b.setB_fkey(aa.getId());
       bDao.persist(b);
   }
   ...
  </code></pre>
  
  <p>This works perfectly, but I want it to be saved in the following X-way:</p>
  
  <pre><code> ...
   A a = new A();
   a.setStuff();
   a.setB(List&lt;B&gt;)
   aDao.persist(a);
   ...
  </code></pre>
  
  <p>now it throws an error "Column 'f_key' cannot be null", because f_key is a foreign key which is referencing not yet generated value of a.id. </p>
  
  <p>Question: how to save it in the "X way"?</p>