【问题标题】:Remove the first entity and its relationship without removing the second entity - Spring Data JPA删除第一个实体及其关系而不删除第二个实体 - Spring Data JPA
【发布时间】:2020-10-19 19:02:05
【问题描述】:

我有两个实体,一个是 UserEntity,另一个是 RoleEntity,用户可以有多个角色,并且该角色可以被多个用户使用,我的实体如下所示:

@Entity
public class UsersEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(nullable = false)
    private Long id;
    //...
    @ManyToMany(mappedBy = "users")
    private Set<RolesEntity> roles;
    //...

    // Getters and setters
}

@Entity
public class RolesEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(nullable = false)
    private Integer id;
    @NotNull
    @Enumerated(EnumType.STRING)
    @Column(length = 20)
    private RoleEnum name;
    @JoinTable(name = "user_roles", joinColumns = {
        @JoinColumn(name = "role_id", referencedColumnName = "id", nullable = false)}, inverseJoinColumns = {
        @JoinColumn(name = "user_id", referencedColumnName = "id", nullable = false)})
    @ManyToMany
    private List<UsersEntity> users;
}

通常角色是固定的,不会发生太大变化。现在我有一个服务:

public void removeUser(Long id) {
    if (userRepository.findById(id).isPresent()) {
        userRepository.deleteById(id);
    } else {
        throw new IllegalArgumentException("User not found!");
    }
}

我的要求是只删除用户而不是与该用户相关的角色,这意味着删除用户和关系。当我调用我得到的预览方法时。

org.postgresql.util.PSQLException: ERROR: update or delete on table "users" violates foreign key constraint "constraint_user_id" on table "user_roles"
  Detail: Key (id)=(4) is still referenced from table "user_roles".

请问有什么技巧可以解决这个问题吗?

【问题讨论】:

    标签: java postgresql jpa spring-data-jpa many-to-many


    【解决方案1】:

    您需要对 UsersEntity 的任何引用为空。

    那么基本上是什么问题?虽然 RolesEntity 引用了 UsersEntity 类,但您不能删除它。最简单的做法是为 UsersEntity 类中的每个 RolesEntity 创建一个循环并从中删除所有内容。

    然后您就可以成功地从您的数据库中删除该用户。

    查看此内容以获取更多信息:How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

    【讨论】:

    • 谢谢你,这对我有帮助,我解决了我在回答中提到的问题。
    【解决方案2】:

    我这样解决了我的问题,我不确定这是否是解决这个问题的最佳方法:

    public void removeUser(Long id) {
        Optional<UsersEntity> userById = usersRepository.findById(id);
        if (userById.isPresent()) {
            UsersEntity user = userById.get();
            for (RolesEntity role : user.getRoles()) {
                role.setUsers(null);
                rolesRepository.save(role);
            }
            usersRepository.delete(user);
        } else {
            throw new IllegalArgumentException("User not found!");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      • 1970-01-01
      • 2018-12-03
      相关资源
      最近更新 更多