時刪除列表的孩子,我有以下實體:休眠@OneToMany更新父
TEAM
@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()
現有之一
我覺得這裏是同樣的問題:http://stackoverflow.com/questions/2011519/jpa-onetomany-not-deleting-child檢查出來! –