[英]Hibernate : how to DELETE Entity referenced by other entities WITH NO Cascade?
i've this two classes: 我有两节课:
@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;
}
The problem is that when i try to DELETE a Team instance i got an error beacause of a Foreign key referenced on TeamMember table. 问题是,当我尝试删除团队实例时,由于在TeamMember表上引用了外键,因此出现了错误。 How to DELETE Team instance correctly without deleting referenced TeamMember? 如何正确删除团队实例而不删除引用的TeamMember? This is the delete method inside TeamController: 这是TeamController内部的delete方法:
public boolean deleteTeam(@NotNull Long id) {
if (!teamDao.existsById(id)) {
return false;
}
teamDao.deleteById(id);
return true;
}
How to DELETE Team instance correctly without deleting referenced TeamMember? 如何正确删除团队实例而不删除引用的TeamMember?
The main idea is to break the relation between the Team Object and its Memebers 主要思想是打破团队对象与其成员之间的关系
Your code can look like this : 您的代码如下所示:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.