title: How to persist Collections/List inside an object using JPA
body: <p>I'm trying to persist a List inside an object Team.  I cannot get JPA to persist it for me.  After having read some posts, it looks like you are required to iterate thru the List&lt;>, and persist each one individually.  This just doesn't seem right to me.  There must be  way for JPA to persist that List's auto-magically.  </p>
  
  <p>Am I missing an easy JPA-way of deeply persisting these objects?</p>
  
  <p>Team class:</p>
  
  <pre><code>@Entity
  @Table(name = "rahCLUB_TEAM")
  public class Team implements Serializable{
  ....
  @OneToMany(fetch=FetchType.EAGER, mappedBy = "team", cascade={CascadeType.PERSIST,  CascadeType.REMOVE})
      private List&lt;Player&gt; players;
  ...
  }
  </code></pre>
  
  <p>Player class:</p>
  
  <pre><code>@Entity
  @PrimaryKeyJoinColumn(name="id")
  @Table(name = "rahCLUB_PLAYER")
  
  public class Player extends Individual implements Serializable{
   ...
     @ManyToOne
     @JoinTable(name="rahCLUB_PLAYER_TEAM_LINK")
     private Team team;
   ...
   }
  </code></pre>
  
  <p>JPAClubDAOTest:</p>
  
  <pre><code>//create a valid team code
   ...
   Team team = new Team();
   team.setName("Pittsburgh Pirates");
   team.setLeague("NFL");
   team.setGroup("group");
   team.setLevel("AAA");
  
   Player player = new Player();
   player.setFirstName("firstNameA");
   player.setLastName("lastNameA");
   player.setEmail("emaila@email.com");
   player.setLogin("loginA");
   player.setJerseyNo(22);
   player.setPosition("fullback");
   Date dob  =new SimpleDateFormat("dd/MM/yyyy").parse("21/11/1986");
   player.setDob(dob);
  
   Player playerb = new Player();
   playerb.setFirstName("firstNameB");
   playerb.setLastName("lastNameB");
   playerb.setEmail("emailB@email.com");
   playerb.setLogin("loginB");
   playerb.setJerseyNo(15);
   playerb.setPosition("widereceiver");
   Date dobb  =new SimpleDateFormat("dd/MM/yyyy").parse("06/06/1986");
   playerb.setDob(dobb);
  
   ArrayList&lt;Player&gt; players = new ArrayList&lt;Player&gt;();
   players.add(player);
   players.add(playerb);
  
   team.setPlayers(players);
  
   Team queryTeam = em.find(Team.class, team.getId());
   log.debug("checking coach...");
  </code></pre>
  
  <p>These all fail: </p>
  
  <pre><code>assertTrue(queryTeam.getPlayers().size()&gt;0);
  assertNotNull(queryTeam.getPlayers().get(0));
  assertTrue(queryTeam.getPlayers().size()==2);
  </code></pre>
  
  <p>Code to add this:</p>
  
  <pre><code>@Override
  public void createTeam(Team team) throws ClubDAOException {
  em.persist(team);
  for (Player player : team.getPlayers())
  {
     this.createPlayer(player);
     //em.persist(player);
  }
  </code></pre>