简体   繁体   English

休眠:删除与联接表的多对多关联

[英]Hibernate : Delete Many-to-Many association with join table

I have two tables with the many-to-many association. 我有两个与多对多关联的表。

DB Details: User --> Columns[Id,Name] 数据库详细信息: 用户 ->列[Id,Name]

Role -->Columns[Id,Name] 角色 ->列[Id,Name]

UserRoles --> Columns[UserId,RoleId] UserRoles- >列[UserId,RoleId]

Hibernate Mapping Details: 休眠映射详细信息:

/* User.hbm.xml */
<set name="Roles" table="UserRoles" inverse="true" cascade="all" lazy="false">
    <key column="UserId" />
    <many-to-many column="RoleId" class="Role" />
</set>
…
/* Rols.hbm.xml */
<join table="UserRoles">
    <key column="RoleId" />
    <many-to-one column="UserId" name="user"/>
</join>

When I am trying to delete the user, it is deleting the appropriate records in user and UserRoles, but it is also deleting Roles records which is not required using below code. 当我尝试删除用户时,它正在删除用户和UserRoles中的相应记录,但同时也删除了使用以下代码不需要的Roles记录。

session.delete(user);

Even if I don't have any user in a Role, I want the Role to be there, just delete only records from User and UserRoles tables.How will i achieve this in XML. 即使我在角色中没有任何用户,我也希望角色在那里,只删除User和UserRoles表中的记录,我将如何用XML实现这一点。

That's because of cascade="all" which includes REMOVE. 那是因为包括删除在内的cascade="all" Replace it according to what you really need. 根据您的实际需要更换它。 See this for details. 请参阅了解详情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM