我有以下实体:
球队
@Entity @Table public class Team { [..] private Set<UserTeamRole> userTeamRoles; /** * @return the userTeamRoles */ @OneToMany(cascade = { CascadeType.ALL }, mappedBy = "team", fetch = FetchType.LAZY) public Set<UserTeamRole> getUserTeamRoles() { return userTeamRoles; } /** * @param userTeamRoles * the userTeamRoles to set */ public void setUserTeamRoles(Set<UserTeamRole> userTeamRoles) { this.userTeamRoles = userTeamRoles; }
}
和
USER_TEAM_ROLE
@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; } }
现在,当使用{UTR1,UTR3}更新包含例如Team.userTeamRoles = {UTR1,UTR2}的Team实体时,我希望删除UTR2。但是我现在的方法是,旧列表保持不变,并且只将UTR3添加到列表中。
这是我目前的做法:
if (!usersDualListData.getTarget().isEmpty()) { // the role for each user within the team will be "employee" team.setUserTeamRoles(new HashSet<UserTeamRole>()); 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);
我认为通过执行team.setUserTeamRoles(new HashSet<UserTeamRole>());该列表将被重置,并且由于级联,先前的列表将被删除。
team.setUserTeamRoles(new HashSet<UserTeamRole>());
任何帮助表示赞赏。谢谢
clear()
team.getUserTeamRoles().clear();
@OneToMany(orphanRemoval=true)