我有以下实体:

团队

@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_团队_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;
 }
}

Now, when updating a Team entity that contains for example Team.userTeamRoles = {UTR1, UTR2} with {UTR1, UTR3}, I want UTR2 to be deleted. But the way I do it now, the old list remains the same 和 it only adds UTR3 to the list.

目前我是这样做的:

 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);

I thought that by doing team.setUserTeamRoles(new HashSet<UserTeamRole>()); the list would be reset 和 because of the cascades the previous list would be deleted.

如有任何帮助,我们将不胜感激.谢谢

推荐答案

  1. 您不必替换集合(team.setUserTeamRoles(new HashSet<UserTeamRole>());),而必须对现有集合进行clear()操作.这是因为如果Hibernate从DB加载实体(及其集合),它会"管理"它们,即.跟踪它们的更改.通常,当使用Hibernate时,最好not为集合(列表、集合)创建任何setter.只创建getter,并清除它返回的集合,即:

    team.getUserTeamRoles().clear();

  2. 另一件事是,您错过了孤立删除(即从父对象的集合中删除子对象).要启用它,您需要在拥有的实体中添加@OneToMany(orphanRemoval=true).

Database相关问答推荐

如何在同一个表的派生部分引用主键?

芭蕾舞女演员坚持 1:N 关系

如何将 Scylla DB 中的计数器列重置为零?

如果我使用存储过程,我对 SQL 注入免疫吗?

如何打印出 sequelize 实例的表名?

什么是非规范化 mysql 数据库的好方法?

管理数据库中的产品计数

有没有办法为 2 个具有不同包名称的应用程序提供 1 个 Firebase 数据库?

主必须包括表的分区位置错误中的所有列?

在 Oracle 的 Check 语句中使用子查询

当使用多个 WHEN MATCHED 语句时,它们是全部执行,还是只执行一个?

如何将 MySQL Workbench 连接到 Amazon RDS?

对百万行表,MySQL 的 LIKE 查询的性能怎样?

是否应该强制执行参照完整性?

与号 (&) 处的 XML 错误

如何在大型数据库中使用 typeahead.js

在默认路径下使用脚本创建数据库?

如何通过 PHP 和 Linux 使用 pdo 连接到 mssql?

C++ SQL 数据库库比较

对于 N:M 关系,在 MongoDB 中推荐的级联删除等效项是什么?