删除共享子对象时,将通过级联重新保存已删除的对象

时间:2013-06-24 09:39:54

标签: java hibernate jpa

我正在使用Hibernate获取臭名昭着的“已删除的对象将通过级联错误重新保存”,我需要一些帮助来解决它。

实体模型如下:它们之间有一个Person,Team和TeamMembership。一个人可以属于许多团队,一个团队可以通过TeamMembership对象让很多人链接到它。

@OneToMany(mappedBy="team", cascade=CascadeType.ALL, fetch=FetchType.EAGER, orphanRemoval=true)
private List <TeamMembership> teamMemberships;

@OneToMany(mappedBy="person", cascade=CascadeType.ALL, orphanRemoval=true)
private List <TeamMembership> teamMemberships;

TeamMembership

@ManyToOne
@JoinColumn(name="teamId", nullable=false)
private Team team;

@ManyToOne
@JoinColumn(name="personId", nullable=false)
private Person person;

所以基本上TeamMembership是Person和Team的“孩子”。当我从团队方编辑团队成员资格时,一切正常。但是,当我尝试从人员方编辑团队成员资格时,我收到此错误。 我的一些映射注释是不正确的还是我错过了?任何其他解决方案将不胜感激。

编辑: 我通过TeamController在团队一侧处理TeamMemberships,如下所示:

首先我从jsp中获取人ID。我称之为以下方法:

private List<TeamMembership> processMembershipList (Team team, Long[] personIds, String teamRole) {
    List<TeamMembership> memberships = team.getTeamMemberships();
    boolean isNewTeam = false;

    if (team.getId() == null) {
        isNewTeam = true;
    }

    for (Long personId: personIds) {
        TeamMembership teamMembership = null;
        Person person = personService.getPerson(personId);
        if (!isNewTeam) {
            teamMembership = teamMembershipService.getTeamMembership(team, person, teamRole);
        }
        if (teamMembership == null) {
            teamMembership = new TeamMembership();
            teamMembership.setPerson(person);
            teamMembership.setTeam(team);
            teamMembership.setTeamRole(teamRole);
        }

        memberships.add(teamMembership);
    }
    return memberships;
}

最后:

teamService.saveTeam(team);

在Person方面,我通过Person Controller执行相同的操作:

获取团队ID并调用以下方法来处理团队成员资格:

private List<TeamMembership> processTeamMembershipList (Person person, Long[] teamIds, String teamRole) {
    List<TeamMembership> memberships = person.getTeamMemberships();
    boolean isNewPerson = false;

    if (person.getId() == null) {
        isNewPerson = true;
    }

    for (Long teamId: teamIds) {
        TeamMembership teamMembership = null;
        Team team = teamService.getTeam(teamId);
        if (!isNewPerson) {
            teamMembership = teamMembershipService.getTeamMembership(team, person, teamRole);
        }
        if (teamMembership == null) {
            teamMembership = new TeamMembership();
            teamMembership.setPerson(person);
            teamMembership.setTeam(team);
            teamMembership.setTeamRole(teamRole);
        }

        memberships.add(teamMembership);
    }
    return memberships;
}

最后:

personService.savePerson(person);

0 个答案:

没有答案