title: How to populate foreign key values in a Hibernate + Spring JPA configuration when parent/child objects are persisted at the same time?
body: <p>I have two objects, Parent and Child.  Child has a foreign key back to PARENT_ID field in PARENT table (MySQL database).</p>
  
  <p>When a Parent and Child object are created/assembled at the same time, and persist is called, the Child PARENT_ID foreign key is not automatically populated.  </p>
  
  <p>Sample Code:</p>
  
  <pre><code>@Entity
  @Table(name = "PARENT")
  public class Parent {
      @Column(name = "PARENT_ID")
      private Long parentId;
  
      @OneToMany(mappedBy = "parent")
      private List&lt;Child&gt; children;
  }
  
  @Entity
  @Table(name = "CHILD")
  public class Child {
      @Column(name = "CHILD_ID")
      private Long childId;
  
      @Column(name = "PARENT_ID")
      private Long parentId;
  
      @ManyToOne
      @JoinColumn(name = "parent_id")
      private Parent parent;
  }
  </code></pre>
  
  <p>I have two samples for persistence:</p>
  
  <p>1) Using a Hibernate EntityManager: </p>
  
  <pre><code>@PersistenceContext
  EntityManager em;
  
  ...
  
  em.persist(parent);
  </code></pre>
  
  <p>2) Using a Spring Data JPA JpaRepository instance:</p>
  
  <pre><code>public interface ParentRepository extends JpaRepository&lt;Parent, Long&gt; {
  
  }
  </code></pre>
  
  <p>And in my ParentServiceImpl:</p>
  
  <pre><code>@Autowired
  private ParentRepository parentRepository;
  
  ...
  
  public Parent save(Parent parent) {
      return parentRepository.save(parent);
  }
  </code></pre>
  
  <p>What is the recommended strategy to go about populating the foreign key?  Should the Parent object be persisted first and then the Child object foreign key set at that point?  Or is there a way to persist it all at once with the foreign key being set automatically or by reference?</p>
  
  <p>Edit: Persistence samples added.</p>
  
  <p><strong>Edit 2 (fixed!): Problem solved as per Ryan Stewart's second point.  I removed the Long parentId field from the Child object and put the @Column reference for the parentId on the getter.  Also made sure to set-up references correctly (importantly Child reference back to Parent).</strong></p>