Adding associated entities in Spring Data JPA
<p>I have a JPA entity <em>Person</em> and an entity <em>Team</em>. Logically Person and Team have a <em>ManyToMany</em> relationship. But because I have an additional attribute, the role of the person in the team, that qualifies the relation, I have to model the relation as two relations to a join-entity, which I called <em>PersonToTeam</em>. Here is the code:</p>

<pre><code>public class Person {
    @Id
    private String id;
    private String name;
    @OneToMany(mappedBy = "id.person", cascade = { CascadeType.ALL })
    private List&lt;PersonToTeam&gt; teamAssociations = new ArrayList&lt;&gt;();
}

public class Team {
    @Id
    private String id;
    private String name;
    @OneToMany(mappedBy = "id.team", cascade = { CascadeType.ALL })
    private List&lt;PersonToTeam&gt; teamAssociations = new ArrayList&lt;&gt;();
}

public class PersonToTeam {
    @EmbeddedId
    private PersonToTeamId id = new PersonToTeamId();
    private RoleInTeam role;

    public enum RoleInTeam {
        ADMIN, MEMBER
    }
}

public class PersonToTeamId implements Serializable {
    private static final long serialVersionUID = -8450195271351341722L;
    @ManyToOne
    private Person person;
    @ManyToOne
    private Team team;
}
</code></pre>

<p>So far so good. But what I do not like is the effort to add an admin to a team. This looks like:</p>

<pre><code>Person person = new Person();
person.setId("d022051");
person.setName("Gregor Frey");
personRepo.save(person);

Team team = new Team();
team.setId("SpringTutorial");
team.setName("Spring Tutorial");

PersonToTeam assoc = new PersonToTeam();
assoc.getId().setPerson(person);
assoc.getId().setTeam(team);
assoc.setRole(RoleInTeam.ADMIN);

List&lt;PersonToTeam&gt; teamAssociations = person.getTeamAssociations();
teamAssociations.add(assoc);
List&lt;PersonToTeam&gt; personAssociations = team.getTeamAssociations();
personAssociations.add(assoc);

teamRepo.save(team);
</code></pre>

<p>I would like to have a method <em>addAdminToTeam</em> which takes a person, creates a new personToTeam association and adds it to the set of of associated persons in the team. </p>

<p>My question is: where should I put this method? In the entity, as a transient setter? In the repository (is that possible at all)? Or in a separate service object? Are there other ways to simplify the procedure?</p>