当我从 users
表中删除一个用户时,他所有的 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)
,但没有帮助。
更新:
我的想法是,我想保留表的当前架构。
不向 BlogUser
类添加帖子和/或评论。
最佳答案
需要给BlogUser
添加级联侧面也是为了将其删除级联到Post
& Comment
.
将类似的内容添加到您的 BlogUser
类:
@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<>();
关于postgresql - JPA:如何从其他表中删除用户和所有引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48465298/