Set-to-many bend and cascade = delete

I have a mapping (only important parts):

<class name = "xyz.Role" table = "ROLE" lazy = "true">
  <id name = "id" type = "java.lang.Integer">
    <column name = "ROLE_ID" />
    <generator class = "increment" />
  </id>
  <set name = "assignments" lazy = "true" table = "PERSON_ROLE" cascade = "delete" 
inverse = "true">
    <key column = "ROLE_ID" />
    <many-to-many class = "xyz.Person" column = "PERSON_ID" />
  </set> 
</class>

and

<class name = "xyz.Person" table = "PERSON" lazy = "true">
  <id name = "Id" type = "java.lang.Integer">
    <column name = "TPP_ID" />
    <generator class = "increment" />
  </id>

  <set name = "roles" lazy = "true" table = "PERSON_ROLE" cascade = "save-update">
    <key column = "PERSON_ID" />
    <many-to-many class = "xyz.Role" column = "ROLE_ID" />
  </set> 
</class>

In this comparison, when I delete a role, the person with this role is also deleted. What I would like to achieve is to remove the association (a row from the PERSON_ROLE table) when I delete the role. Is there any way to achieve this?

+3
source share
3 answers

. Person_Role , AFAIK.

" " Person_Role Role.

- sfussenegger - . , , Person_Role . , . Hibernate , inverse="true" . , , Person.roles, Role.assignments:

for (Person p : role.assignments) {
    person.roles.remove(role)
}

, , " " , . . , : " 30% QA 70% ", .

+9

role.getAssignments().clear() ?

for (Person p : role.getAssignments()) {
    person.getRoles.remove(role)
}
role.getAssignments.clear();
session.delete(role);

cascade="delete". , XML, :)

+1

Role . , HQL. :

<set name="assignments" lazy="true" table="PERSON_ROLE" cascade="delete" 
    inverse="true">
    <key column="ROLE_ID" />
    <many-to-many class="xyz.Person" column="PERSON_ID" />
</set>

And whenever you need people for a role (which, I think, should be rare), get:

SELECT p FROM Person p JOIN p.roles WHERE role=:role
0
source

Source: https://habr.com/ru/post/1732848/


All Articles