ManyToMany关系,从关系表中删除记录 [英] ManyToMany relationship, deleting records from relationship table

查看:168
本文介绍了ManyToMany关系,从关系表中删除记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我从2h开始尝试为以下问题提出解决方案,但我找不到合适的方法在MySQL数据库中有三个表:

角色
[角色名称] [角色名称]



权限
[permission_id] [permission_name]

PermissionToRole
[permission_id] [role_id]



我有Role类作为关系的所有者:

  @ManyToMany(cascade = {CascadeType.MERGE,CascadeType.PERSIST, CascadeType.REFRESH})
@JoinTable(name =permissiontorole,
joinColumns = {@ JoinColumn(name =role_id)},
inverseJoinColumns = {@ JoinColumn(name =permission_id )})

Permission类映射定义为:

  @ManyToMany(mappedBy =permissions)
private Set< UserRole> userRoles = new HashSet< UserRole>();

现在,当我删除权限或角色时,相应的记录将从其表中删除和期望),但关系仍然在PermissionToRole表中,我不知道如何删除任何时候删除角色或权限记录。当我将级联类型更改为ALL时,那么当我删除角色或权限时,关系将被删除,但其他记录也是如此。如果我删除角色的权限也被删除。



任何想法如何处理它?<​​b>

解决方法

您只需从 Role.permissions 集合中删除权限,即可删除角色和权限之间的关联:

  for(UserRole role:permissionToDelete.getUserRoles()){
role.getPermissions()。remove(permissionToDelete);
}
em.remove(permissionToDelete);


Since 2h I'm trying to come up with the solution for the following problem, and I just can't find a proper way to do it:

I have three tables in MySQL db:

Role [role_id] [role_name]

Permission [permission_id] [permission_name]

PermissionToRole [permission_id] [role_id]

I have the Role class as the owner of the relationship:

@ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
@JoinTable(name="permissiontorole", 
            joinColumns={@JoinColumn(name="role_id")}, 
            inverseJoinColumns={@JoinColumn(name="permission_id")})

The Permission class mapping defined as:

@ManyToMany(mappedBy="permissions")
private Set<UserRole> userRoles = new HashSet<UserRole>(); 

Now, when I delete either permission or role those respective records are removed from their tables (this is expected and desired), but the relationship still remains in PermissionToRole table and I have no clue how to remove that whenever I delete either Role or Permission record. when i change the cascade type to ALL, then when i remove role or permission the relationship is removed but so is the other record e.g. if i remove role the permission is also removed.

Any ideas how to deal with it?

解决方案

You simply need to remove the permission from the Role.permissions collection, to remove the association between the role and the permission:

for (UserRole role: permissionToDelete.getUserRoles()) {
    role.getPermissions().remove(permissionToDelete);
}
em.remove(permissionToDelete);

这篇关于ManyToMany关系,从关系表中删除记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆