简体   繁体   English

JPA多对多关系:删除具有活动关系的子实体

[英]JPA Many-to-Many relation: delete child entity not possible with active relation

In a db, I have User and Role entities. 在数据库中,我有UserRole实体。 The share a many-to-many relation as a Role entity can be assigned to multiple User entities and on the other hand a User entity can be assigned to multiple Role entities. 作为Role实体的多对多关系的共享可以分配给多个User实体,另一方面可以将User实体分配给多个Role实体。

My entity classes look like this 我的实体类看起来像这样

UserEntity UserEntity

@Entity
public class UserEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @Column(unique = true, nullable = false)
    private String username;
    @ManyToMany
    private Set<RoleEntity> roles;

    ...
}

RoleEntity RoleEntity

@Entity
public class RoleEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @Column(unique = true, nullable = false)
    private String name;
    @ManyToMany(mappedBy = "roles")
    private Set<UserEntity> users;

    ...
}

With this configuration I am able to map the entities with each other. 通过这种配置,我可以相互映射实体。 I am also able to delete a User entity. 我也可以删除User实体。 But I am not able to delete a Role entity as long as a relation exists. 但只要存在关系,我无法删除Role实体。

If I add cascade = CascadeType.REMOVE the Role gets deleted, but with it the User too of course. 如果我添加cascade = CascadeType.REMOVE ,则会删除Role ,但当然也会删除User

To only way to get this working currently is to define a @JoinTable on both sides. 目前唯一能够实现此目的的是在两侧定义@JoinTable But this seems more like a workaround. 但这似乎更像是一种解决方法。 What am I doing wrong? 我究竟做错了什么? As this is a regular use case, there got to be solution to this, although I haven found it yet... 由于这是一个常规用例,因此必须有解决方案,尽管我还没有找到它......

You need the join table, it's not a work around. 你需要连接表,这不是一个解决方法。 Remember you are mapping your object oriented model to a relational model. 请记住,您正在将面向对象的模型映射到关系模型。 The only way to express many-to-many relationship in the relational model is defining a @JoinTable. 在关系模型中表达多对多关系的唯一方法是定义@JoinTable。

UPDATE: Adding comment in the answer 更新:在答案中添加评论
You sould define the @JoinTable just in one entity, for example UserEntity and mappedBy="roles" in RolesEntity inherits the definitions of @JoinColumn and @JoinTable names. 您定义前人的精力在@JoinTable只是一个实体,例如UserEntitymappedBy="roles"RolesEntity继承的定义@JoinColumn@JoinTable名。

Then you need to define the cascade operations you want to perform in both sides of the relationship. 然后,您需要定义要在关系的两侧执行的级联操作。

In RoleEntity RoleEntity

@ManyToMany(mappedBy = "roles")
private Set<UserEntity> users;

In UserEntity UserEntity

@ManyToMany
@JoinTable(...)
private Set<RoleEntity> roles;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM