Pergunta

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?

Foi útil?

Solução

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);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top