This is a question about Hibernate’s generated sql about deleting one relationship under many-to-many mapping, not ‘cascade’ problem.
I use JPA 2 and hibernate as its implementation.
I have two models, User and Role. One user can have many role, and one role can have many users, so they are many-to-many mapping:
@Entity
class User{
@Id Long id;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
@JoinTable(name = "user_role", inverseJoinColumns = @JoinColumn(name = "role_id"),
joinColumns = @JoinColumn(name = "user_id"))
private List<Role> roles;
}
@Entity
class Role{
@Id Long id;
@ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.REFRESH, mappedBy = "roles")
private List<User> users;
}
and the mapping works well , hibernate auto create three tables for this mapping
table user
table role
table user_role
Now here is the problem, what I want is just remove one role from one user (not remove a user or a role, just one relation between one user and one role, means only need remove one record from the table user_role). Here is the code I tried:
public void removeOneRoleFromUser(long userId, long roleId){
User user = userService.getById(userId);
Role role = roleService.getById(roleId);
user.getRoles().remove(role); //here
userService.update(user);
}
when I execute this code it work, the role was removed the from the user indeed. But when I check the sql which hibernate generated for it, it’s not what I expected, The hibernate generated sql is:
delete from user_role where user_id = {userId}
insert into user_role values({user_id}, {role_id_not_removed})
...
insert into user_role values({user_id}, {another_role_id_not_removed})
So for deleting one role from one user, hibernate first delete all roles from the user, then add those role which should not be removed back to the user one by one.
And what I expect is just one sql sentence archive it:
delete from user_role where user_id = {userId} and role_id = {role_id}
I know there is some other ways I can archive this like introducing another entity UserRoleMapping which mapping to the table user_role, then directly remove one UserRoleMapping instance will remove one role from one user; but I want to know is there any solution I can get the expect with the current solution.
I’ve not checked that this explanation is true, but it has good points.
Without any index column, a List is in fact a bag: no order, and duplicates allowed. So Hibernate considers it possible that you have the same role twice in the list of roles of a user.
So issuing
delete from user_role where user_id = ? and role_id = ?is not possible because it would potentially remove several roles instead of just the one you removed from the list.Try adding an index column, or using a
Set<Role>instead of aList<Role>.