具有 Spring 安全性的用户和用户角色之间的外键

ForeignKey between User and UserRole with Spring Security

实际上我有一个与 rbac 一起使用的身份验证。 问题是,我遇到了一个用户被删除的情况,但在数据库中,用户ID和角色仍然存在。

重新创建用户后,他获得了具有此 ID 的前用户的角色。 实际上我无法删除已删除用户的用户角色,因为它是一个枚举..

是否可以在保持这种枚举原则的同时建立用户和角色之间的关系?或者其他解决方案?

public class AppUser {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    ....

    @ElementCollection(fetch = FetchType.EAGER)
    @Enumerated(EnumType.STRING)
    List<AppUserRole> appUserRoles;
    
}
public enum AppUserRole implements GrantedAuthority {
    ROLE_ADMIN, ROLE_DEMO;

    public String getAuthority() {
        return name();
    }

}

下面是如何为 @ElementCollection 创建角色 table 的示例(PostgreSQL 语法):

CREATE TABLE user_roles (
  user_id int,
  role text,
  PRIMARY KEY (user_id, role),
  FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
);

具有 ON DELETE CASCADE 的外键确保在删除用户时删除关联的角色。

删除带有 @ElementCollection 的实体时,删除会自动级联。通过 SQL 执行此操作时,情况(可能)并非如此,具体取决于级联规则在您的数据库中的应用方式。

但是根据您的设置应该会自动发生。

另见