title: Why do I have to persist both objects if Address is nested in User?
body: <p>I am trying to better familiarize myself with JPA so I created a very simple project.  I have a User Class and an Address class.  It appears that I have to persist both even though I am adding Address to my User class?</p>
  
  <p>User:</p>
  
  <pre><code>import javax.persistence.*;
  import java.util.HashSet;
  import java.util.List;
  import java.util.Set;
  
  @Entity
  @Table(name = "usr") // @Table is optional, but "user" is a keyword in many SQL variants 
  @NamedQuery(name = "User.findByName", query = "select u from User u where u.name = :name")
  public class User {
      @Id // @Id indicates that this it a unique primary key
      @GeneratedValue // @GeneratedValue indicates that value is automatically generated by the server
      private Long id;
  
      @Column(length = 32, unique = true)
      // the optional @Column allows us makes sure that the name is limited to a suitable size and is unique
      private String name;
  
      // note that no setter for ID is provided, Hibernate will generate the ID for us
  
      @OneToMany(fetch=FetchType.LAZY, mappedBy="user")
      private List&lt;Address&gt; addresses;
  </code></pre>
  
  <p>Address:</p>
  
  <pre><code>@Entity
  public class Address {
  
      @Id // @Id indicates that this it a unique primary key
      @GeneratedValue // @GeneratedValue indicates that value is automatically generated by the server
      private Long id;
  
      @Column(length=50)
      private String address1;
  
      @ManyToOne
      @JoinColumn(name="user_id")
      private User user;
  </code></pre>
  
  <p>EntityManager:</p>
  
  <pre><code>EntityManager entityManager = Persistence.createEntityManagerFactory("tutorialPU").createEntityManager();
  
  entityManager.getTransaction().begin();
  
  User user = new User();
  user.setName("User");
  
  List&lt;Address&gt; addresses = new ArrayList&lt;Address&gt;();
  Address address = new Address();
  address.setAddress1("Address1");
  
  addresses.add(address);
  user.setAddresses(addresses);
  entityManager.persist(user);
  entityManager.persist(address);
  entityManager.getTransaction().commit();
  entityManager.close();
  </code></pre>
  
  <p>Probably doing something wrong...just not sure what it is?</p>
  
  <p>Any suggestions would be appreciated.  </p>
  
  <p>Thanks,</p>
  
  <p>S</p>