Hibernate:如何删除其他实体引用的实体没有Cascade?

时间:2018-06-03 18:01:10

标签: java spring hibernate spring-data-jpa sql-delete

我有这两个班:

    @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;
        }

1 个答案:

答案 0 :(得分:0)

  

如何在不删除引用的情况下正确删除Team实例   TeamMember?

  1. 首先,你必须找到团队对象
  2. 对于此团队的每个TeamMember,将null设置为团队
  3. 清除团队成员名单
  4. 然后删除团队
  5. 主要思想是打破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;            
    }