我有这两个班:
@Entity
@Table(name = "team")
@Getter
@Setter
@NoArgsConstructor
public class Team {
@Id
@GeneratedValue
private Long id;
private String name;
@Enumerated(EnumType.STRING)
private ProblemArea problemArea;
@JsonIgnore
@OneToMany(mappedBy = "team")
@Cascade(value = org.hibernate.annotations.CascadeType.PERSIST)
private List<TeamMember> teamMemberList;
@JsonIgnore
@OneToOne
@Cascade(value = org.hibernate.annotations.CascadeType.PERSIST)
private TeamLeader teamLeader;
}
@Entity
@Table(name = "team_member")
@Getter
@Setter
public class TeamMember extends InternalUser {
@OneToOne
@Cascade(value = org.hibernate.annotations.CascadeType.PERSIST)
protected Team team;
}
问题在于,当我尝试删除Team实例时,由于TeamMember表上引用了外键而出现错误。 如何在不删除引用的TeamMember的情况下正确删除Team实例? 这是TeamController中的delete方法:
public boolean deleteTeam(@NotNull Long id) {
if (!teamDao.existsById(id)) {
return false;
}
teamDao.deleteById(id);
return true;
}
答案 0 :(得分:0)
如何在不删除引用的情况下正确删除Team实例 TeamMember?
主要思想是打破Team Object及其Memebers之间的关系
您的代码可能如下所示:
public boolean deleteTeam(@NotNull Long id) {
//Find the Team by its id
Team team = teamDao.findById(id);
//If the team exist then
if (team != null) {
for (TeamMember member : team.getTeamMemberList) {
//Set null to Team for each Member(Brock the relation between father and sons)
member.setTeam(null);
}
//Make sure that the list of members are empry
team.getTeamMemberList.clear();
//then delete the team
teamDao.deleteById(team.getId());
return true;
}
//Else if the team is null return false
return false;
}