ManyToMany relationship, deleting records from relationship table

自作多情 提交于 2019-12-13 04:37:00

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/20728387/manytomany-relationship-deleting-records-from-relationship-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!