【发布时间】: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