0
Imagine the relationships:
User has Many Permissions
Permission has Many Users
We can create a relationship of N para N
as follows:
User class.
public class User {
/*Many attributes here*/
private List permissions;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "users")
public List getPermissions() {
return permissions;
}
public void setPermissions(List permissions){
this.permissions = permissions;
}
}
Permission.class
public class Permission{
/*Many attributes here..*/
private List users;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
Thus one can affirm a relationship of N pra N
whereas the Owner is the class Permission
.
When I mean the user 1 has the permissions 3 and 5, for example, I do something like this:
User u = (User)session.get(User.class, 1);
List permissions = new ArrayList<>();
permissions.add(new Permission(3));
permissions.add(new Permission(5));
for(Object permission : permissions){
Permission p =
(Permission) session.get(Permission.class, ((Permission)permission).getId());
p.getUsers().add(u);
}
session.getTransaction().commit();
All functioning correctly.
However, when I visualize logs, I see that the Hibernate is first deleting all records from the associative table permission_user
related that permission, then adding everything again. (Once we have access to all previously associated users when we call p.getUsers(); //pega todos os usuários já associados
)
Let’s assume the permission 3 already have the user 100 and the user 101 associated with it, and so I now want to associate the user 1. Us logs, the Hibernate is running more or less like this...
delete from permission_user where id_permission = ? //deve ser id 3
insert into permission_user (id_permission, id_user) values (?, ?) //deve ser 3 e 100 respectivamente
insert into permission_user (id_permission, id_user) values (?, ?) //deve ser 3 e 101 respectivamente
insert into permission_user (id_permission, id_user) values (?, ?) //deve ser 3 e 1 respectivamente
The point is, as I’m associating a new user, my expectation is that the Hibernate can execute the insert
only once (Since the user 100 and 101 are already present in the associative table).
And this occurs for each permission. So, if I say the user 1 will have the permissions, 3, 5, 10, 11, 12, 13, 15, 16 and 19 and each of these permissions already has users associated with it, about 10 users for example, the Hibernate will perform more than 100 instructions to perform what I wish. This is really very problematic.
Someone could give me a light?
Thanks in advance.
I see no need to use Manytomany in your problem. A Onetomany would solve without complications.
– Black