以多对多关系插入连接表

时间:2011-07-13 10:57:06

标签: java hibernate many-to-many

问题#1:

我有三张桌子; UserUserRoleUserRoleRelationships(联接表)。 UserRole表包含我要与用户关联的所有用户角色。当我插入新用户时,我想添加新用户并在连接表中添加新关联。现在,当我运行查询以插入新用户时:

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正在运行以下查询:

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 (?, ?)

我的hibernate映射看起来像:

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>

如何让hibernate在连接表中保存具有现有用户角色的新用户?

问题#2:

当我更新用户时,hibernate删除连接表中的关系。我怎么能避免这个?

1 个答案:

答案 0 :(得分:3)

  

如何让hibernate在连接表中保存具有现有用户角色的新用户?

检索用户角色实体并将其放入列表中,而不是始终创建新的实体。

我的意思是这一部分:

IWUserRole iwUserRole = new IWUserRole();
iwUserRole.setRole("ROLE_USER");

相反,您会发出类似select r from IWUserRole where r.role = 'ROLE_USER'

的查询