title: JPA: Is it possible to persist child objects in the array only when the main object is persisted?
body: <p>I am developing a web application using JSF and JPA(Eclipse link). I have two entities with bidirectional OneToMany relationship. The owner entity is contact and target entity is customer. Single customer can have multiple contacts, like email, phone, etc. When the end user is adding a new customer, he also adds the contacts straight away. There is a need to cancel the saving of a new customer, even after adding contacts to that customer. I tried to add that functionality, but failed in the following way.</p>
  
  <p>Can that senario be achieved directly by persistence?</p>
  
  <p>Contact Entity</p>
  
  <pre><code>....
  public class Contact implements Serializable {
      ....   
      @ManyToOne
      Customer customer;
      ....   
  </code></pre>
  
  <p>Customer Entity</p>
  
  <pre><code>....
  public class Customer implements Serializable {
      ....
      @OneToMany(mappedBy = "customer")
      private List&lt;Contact&gt; contacts;
      ....   
  </code></pre>
  
  <p>Adding a new contact to Customer (current is an object of Customer class)</p>
  
  <pre><code>Contact contact = new Contact();
  contact.setCustomer(current);
  ....
  current.getInstitutionContacts().add(contact);
  </code></pre>
  
  <p>This works when the current is already a persisted one. If I tried to add a contact to yet to persist one, there is a <code>java.lang.NullPointerException</code>.</p>
  
  <p>I can work around to achieve the functionality, but is there any way we can just collect the contacts to the array and persist them only when (and if only) the customer is persisted? By using cascade persist or lazy fetch, etc?</p>