title: Hibernate @OneToMany remove child from list when updating parent
body: <p>I have the following entities:</p>
  
  <p>TEAM</p>
  
  <pre><code>@Entity
  @Table
  public class Team {
  [..]
  private Set&lt;UserTeamRole&gt; userTeamRoles;
  
  /**
   * @return the userTeamRoles
   */
  @OneToMany(cascade = { CascadeType.ALL }, mappedBy = "team", fetch = FetchType.LAZY)
  public Set&lt;UserTeamRole&gt; getUserTeamRoles() {
      return userTeamRoles;
  }
  
  /**
   * @param userTeamRoles
   *            the userTeamRoles to set
   */
  public void setUserTeamRoles(Set&lt;UserTeamRole&gt; userTeamRoles) {
      this.userTeamRoles = userTeamRoles;
  }
  </code></pre>
  
  <p>}</p>
  
  <p>and </p>
  
  <p>USER_TEAM_ROLE</p>
  
  <pre><code>@Entity
  @Table(name = "user_team_role")
  public class UserTeamRole {
  
   @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
   @JoinColumn(name = "FK_TeamId")
   public Team getTeam() {
      return team;
   }
  }
  </code></pre>
  
  <p>Now, when updating a Team entity that contains for example Team.userTeamRoles = {UTR1, UTR2} with {UTR1, UTR3}, I want UTR2 to be deleted. But the way I do it now, the old list remains the same and it only adds UTR3 to the list. </p>
  
  <p>This is how I do it at the moment:</p>
  
  <pre><code> if (!usersDualListData.getTarget().isEmpty()) {
          // the role for each user within the team will be "employee"
          team.setUserTeamRoles(new HashSet&lt;UserTeamRole&gt;());
          Role roleForUser = roleService
                  .getRoleByName(RoleNames.ROLE_EMPLOYEE.name());
          for (User user : usersDualListData.getTarget()) {
              UserTeamRole utr = new UserTeamRole();
              utr.setUser(user);
              utr.setTeam(team);
              utr.setRole(roleForUser);
              team.getUserTeamRoles().add(utr);
          }
      }
  
  teamService.updateTeam(team);
  </code></pre>
  
  <p>I thought that by doing <code>team.setUserTeamRoles(new HashSet&lt;UserTeamRole&gt;());</code> the list would be reset and because of the cascades the previous list would be deleted.</p>
  
  <p>Any help is appreciated. Thank you</p>