简体   繁体   中英

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]

Role -->Columns[Id,Name]

UserRoles --> Columns[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.

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.

That's because of cascade="all" which includes REMOVE. Replace it according to what you really need. See this for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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