Problem number 1:
I have three tables; User , UserRole and UserRoleRelationships (connection table). The UserRole table contains all the user roles that I want to associate with the user. When I insert a new user, I want to add a new user and add a new association to the connection table. Now, when I run a query to insert a new user:
IWUser iwUser = new IWUser(); iwUser.setUsername("username"); iwUser.setFullName("fullName"); iwUser.setEmail("email"); iwUser.setPassword("password"); iwUser.setPrivatephone("55555"); iwUser.setWorkphone("777"); Set<IWUserRole> roleList = new HashSet<IWUserRole>(); IWUserRole iwUserRole = new IWUserRole(); iwUserRole.setRole("ROLE_USER"); roleList.add(iwUserRole); iwUser.setUserRole(roleList); iwUserManagementService.saveOrUpdate(iwUser);
hibernate runs the following queries:
Hibernate: insert into dbo.Users (Username, Password, Email, Workphone, Privatephone, FullName) values (?, ?, ?, ?, ?, ?) Hibernate: insert into dbo.UserRoles (Role) values (?) Hibernate: insert into UserRoleRelationships (UserId, RoleId) values (?, ?)
My hibernation mapping is as follows:
IWUser.hbm.xml :
<hibernate-mapping> <class name="domain.IWUser" 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="all" inverse="false" name="userRole" table="UserRoleRelationships" lazy="true" > <key> <column name="UserId"/> </key> <many-to-many class="domain.IWUserRole" column="RoleId"/> </set> </class> </hibernate-mapping>
IWUserRole.hbm.xml :
<hibernate-mapping> <class name="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="all" inverse="false" name="user" table="UserRoleRelationships" lazy="true"> <key> <column name="RoleId"/> </key> <many-to-many class="domain.IWUser" column="UserId"/> </set> </class> </hibernate-mapping>
How do I get hibernation to save a new user with an existing user role in the connection table?
Problem number 2:
When I update the user, hibernate deletes the relations in the connection table. How can i avoid this?