我有两个实体“Person”和“Team”,它们使用注释通过多对多关系映射,如下所示:
@Entity
public class Perosn implements Serializable {
....
private Collection<Team> teams;
....
@ManyToMany(fetch = FetchType.LAZY)
@Cascade({CascadeType.ALL})
@JoinTable(name = "person_team",
joinColumns = { @JoinColumn(name = "person_id")},
inverseJoinColumns = {@JoinColumn(name = "team_id")})
public Collection<Team> getTeams() {
return advisers;
}
}
@Entity
public class Team implements Serializable {
....
private Collection<Person> persons;
....
@ManyToMany(fetch = FetchType.LAZY)
@Cascade({CascadeType.ALL})
@JoinTable(name = "person_team",
joinColumns = { @JoinColumn(name = "team_id")},
inverseJoinColumns = {@JoinColumn(name = "person_id")})
public Collection<Person> getPersons() {
return advisers;
}
}
我使用以下服务类将新团队添加到人员对象并更新连接表(添加包含 personId 和 teamId 的新记录):
@Service("teamService")
public class TeamService extends DataAccess {
....
public void addTeamToPerson(String teamId, String personId) {
Team team= getTeam(teamId);
Person person= personService.getPerson(personId);
person.getTeams().add(team);
super.update(team);
}
....
}
public abstract class DataAccess<E> {
private EntityManager manager;
....
public void update(E object) {
try {
manager.getTransaction().begin();
manager.merge(object);
manager.getTransaction().commit();
} catch (Exception e) {
....
}
}
....
}
这种结构确实有效,但我认为将团队对象添加到人员对象的团队集合并更新团队对象很奇怪。逻辑上是错的吗?我需要知道在这种类型的关系中存在主从功能或类似的东西。
任何指南都将被视为。