Hi Folks,
Spent 2 hours searching for a straight answer on this but cant find one.... Hope u can help. Its regarding loads of delete and inserts being generated when i modify a set.
I have an Group class that contains a many-to-many relationship with a User class. This relationship has an attribute of role (I.e. a user has a specific role in a group) When I want to add a new user to the group I am doing the following:
getGroup
getGroupUserSet
getUser
groupUserSet.add(User)
group.setGroupUserSet(groupUserSet)
save()
**Real code posted at end**
The Question
When i check the SQL generated as a rules of this hibernate does a series of deletes (to remove all the original relationships in the set) then a series of inserts (to add all the previous ones PLUS the new one).
Is this normal behaviour? It feels very expensive.
Hope you can help....Aidan
Code:
Set<GroupRole> assignedUserRoles;
OperationalGroup group = userDao.getOperationalGroup(groupId);
User user = userDao.getUserById(userId);
GroupRole newGR = new GroupRole();
newGR.setGroupRole(role);
newGR.setUser(user);
assignedUserRoles = group.getAssignedUserRoles();
assignedUserRoles.add(newGR);
group.setAssignedUserRoles(assignedUserRoles);
userDao.saveOperationalGroup(group);
and the SQL generated
Code:
12:46:42,011 DEBUG SQL:111 -
delete
from
user_to_group_role
where
group_id=?
and user_id=?
and group_role=?
12:46:42,012 DEBUG SQL:111 -
delete
from
user_to_group_role
where
group_id=?
and user_id=?
and group_role=?
12:46:42,016 DEBUG SQL:111 -
delete
from
user_to_group_role
where
group_id=?
and user_id=?
and group_role=?
<SNIP>loads more deletes</SNIP>
12:46:42,019 DEBUG SQL:111 -
insert
into
user_to_group_role
(group_id, user_id, group_role)
values
(?, ?, ?)
<SNIP>loads more inserts</SNIP>
mapping file
Code:
<class name="OperationalGroup" table="operational_groups">
<id name="groupId" column="group_id"/>
<property name="groupType" column="group_type"/>
<property name="description" column="description"/>
<property name="groupActive" column="group_active"/>
<many-to-one name="owner" class="User" column="owner_user_id" unique="true"/>
<many-to-one name="escalationOne" class="Contact" column="escalation_one_contact_id" unique="true"/>
<many-to-one name="escalationTwo" class="Contact" column="escalation_two_contact_id" unique="true"/>
<many-to-one name="escalationThree" class="Contact" column="escalation_three_contact_id" unique="true"/>
<set name="dataRoles" table="operational_groups_to_roles">
<key column="group_id"/>
<many-to-many column="role_name" class="DataRole"/>
</set>
<set name="assignedUserRoles" table="user_to_group_role">
<key column="group_id"/>
<composite-element class="GroupRole" >
<many-to-one name="user" column="user_id" class="User"/>
<property name="groupRole" column="group_role"/>
</composite-element>
</set>
</class>