JPA:如何从其他表中删除用户和所有引用?

JPA: How to remove user and all references from other tables?

当我从 users table 中删除一个用户时,他的所有 posts 和此帖子的任何 comments 也应该被删除。

模型如下所示:

@Data
@Entity @Table(name = "users")
public class BlogUser {

    @Id
    private String userName;
    private String password;
    private String email;

    @Enumerated(EnumType.STRING)
    private Role role;

    private boolean enabled;
}

post 实例引用了所属用户:

@Data
@Entity @Table(name = "posts")
public class Post {

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

    private String postText;

    @ManyToOne(cascade = CascadeType.ALL)
    private BlogUser user;

    private LocalDateTime createdDate;
}

同样的情况也适用于评论。

现在,当我想要执行删除时,出现了这个错误:

org.postgresql.util.PSQLException: ERROR: update or delete on table "users" violates foreign key constraint "fkqdk379brhxkbj4c8qenbuu85l" on table "posts"

数据库是 Postgres。我尝试使用 @ManyToOne(cascade = CascadeType.ALL),但没有用。

更新:

我的想法是,我想将当前架构保留 table 秒。
不向 BlogUser class 添加帖子 and/or 条评论。

您的问题很可能是因为您没有在表上声明 ON CASCADE。基本上你需要在用户 / posts 和 posts / 评论之间删除你的 id 约束,并在末尾添加 ON CASDADE DELETE 重新创建它们。 This 应该能帮到你。

或者,如果您不想这样做,您显然可以删除用户 ID 与您想要的匹配的 post / 评论,然后删除所述用户。如果您更喜欢此解决方案,This 也应该对您有所帮助。

您还需要将级联添加到 BlogUser 端,以便在其上进行删除以级联到 Post & Comment

将这样的内容添加到您的 BlogUser class:

@Getter
@OneToMany(cascade=CascadeType.ALL, mappedBy="user")
private Collection<Post> posts = new HashSet<>();

@Getter
@OneToMany(cascade=CascadeType.ALL, mappedBy="user")
private Collection<Comment> comments = new HashSet<>();