I got three tables; User, UserRole and UserRoleRelationships (join table).
Both insert and delete for user with roles works great, but when I'm trying to update a user without inserting roles, hibernate delete all records for the corresponding user in the join table.
I have also tried to select all user roles and the insert them into the new user. This will give me the following exception:
Quote:
Illegal attempt to associate a collection with two open sessions
User.hbm.xml:
Code:
<class name="User" schema="dbo" table="Users">
<id name="userId" type="int">
<column name="UserId"/>
<generator class="native"/>
</id>
<property name="username" type="string">
<column name="Username" not-null="true"/>
</property>
<property name="password" type="string">
<column name="Password" not-null="true"/>
</property>
<property name="email" type="string">
<column name="Email" not-null="false"/>
</property>
<property name="workphone" type="string">
<column name="Workphone" not-null="false"/>
</property>
<property name="privatephone" type="string">
<column name="Privatephone" not-null="false"/>
</property>
<property name="fullName" type="string">
<column name="FullName" not-null="false"/>
</property>
<set cascade="save-update" inverse="false" name="userRole" table="UserRoleRelationships" lazy="true" >
<key>
<column name="UserId"/>
</key>
<many-to-many class="UserRole" column="RoleId"/>
</set>
</class>
</hibernate-mapping>
UserRole.hbm.xml:
Code:
<hibernate-mapping>
<class name="sergelintraweb.domain.IWUserRole" schema="dbo" table="UserRoles">
<id name="roleId" type="int">
<column name="RoleId"/>
<generator class="native"/>
</id>
<property name="role" type="string">
<column name="Role" not-null="true"/>
</property>
<set cascade="save-update" inverse="false" name="user" table="UserRoleRelationships" lazy="true">
<key>
<column name="RoleId"/>
</key>
<many-to-many class="sergelintraweb.domain.IWUser" column="UserId"/>
</set>
</class>
</hibernate-mapping>
Code for updating user:
Code:
IWUser iwUser = new IWUser();
iwUser.setUserId(1);
iwUser.setUsername("john");
iwUser.setFullName("john doe");
iwUser.setEmail("email");
iwUser.setPassword("password");
iwUser.setPrivatephone("4");
iwUser.setWorkphone("4");
Set<IWUserRole> role = iwUserManagementService.getUserAndRolesWithId(1).get(0).getUserRole();
iwUser.setUserRole(role);
iwUserManagementService.saveOrUpdate(iwUser);
Please help :)