【发布时间】:2018-01-26 16:17:03
【问题描述】:
当我从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;
}
同样的情况也适用于 cmets。
现在当我想执行删除时,我收到了这个错误:
org.postgresql.util.PSQLException:错误:更新或删除表“users”违反了表“posts”上的外键约束“fkqdk379brhxkbj4c8qenbuu85l”
DB 是 Postgres。我尝试使用@ManyToOne(cascade = CascadeType.ALL),但没有帮助。
更新:
这个想法是我想保留表的当前架构。
无需将帖子和/或 cmets 添加到 BlogUser 类。
【问题讨论】:
-
在休眠方面似乎没问题,您的数据库模式是从休眠类生成的还是相反?还是都手动创建?
-
@Tapaka DB 是手动创建的。以及应用程序生成的所有表。我正在使用 Spring Boot 应用程序。
标签: postgresql hibernate jpa sql-delete cascade