级联的ManyToMany只能以一种方式级联 [英] ManyToMany with cascade all only cascading one way
问题描述
我有2个实体: 1)用户 2)部门.
I have 2 entities: 1) User 2) Department.
每个都包含另一个SET,因为它们之间的关系是manyToMany,
each contains a SET of the other since the relationship between them is manyToMany,
我在用户实体和部门实体上以及当我这样做时都标记了(CascadeType.ALL):
I marked (CascadeType.ALL) on the user entity and the department entity and when i do :
userX.getDepartments.remove(departmentX);
save(userX);
它的工作原理与预期的一样-实际上暗示着
it works like intended - it actually implies that
departmentX.getUsers.contains(userX) == false.
被隐式调用.
但是,当我这样做
departmentY.getUsers.remove(userX);
save(departmentY);
它没有级联! 含义-我可以做到
it doesn't cascade! meaning - i can do
userX.getDepartments.contains(departmentY) == true
有什么想法为什么级联都只能以一种方式起作用? 有解决办法吗?
any ideas why the cascade all works only one way? is there a solution?
谢谢
推荐答案
级联与您正在执行的操作无关.级联的意思是:当我保存X时,也保存Y.
The cascade is irrelevant to what you're doing. Cascading means: when I save X, also save Y.
您有一个ManyToMany双向关联.关联的所有者是用户.这意味着对User.departments
集合的每次更改都将保存到数据库中.另一面(Department.users
)是反面.这意味着Hibernate将忽略对Department.users
的所有更改.
You have a ManyToMany bidirectional association. The owner side of the asociation is User. This means that every change to the User.departments
collection will be saved into the database. The other side (Department.users
) is the inverse side. This means that every change to Department.users
will be ignored by Hibernate.
您有责任在所有者端执行操作,并且最好将关联双方保持一致状态:将用户从部门中撤离时,部门也应从用户中撤离,并且反之亦然. Hibernate并不在乎双方是否处于一致状态:它保留了关联的所有者方(没有mappedBy
属性的那一方)的状态
It's YOUR responsibility to xecute the operations in the owner side and, preferrably, to maintain both sides of the association in a coherent state: when a user is removed from a department, the department should also be removed from the user, and vice-versa. Hibernate doesn't care if both sides are in a coherent state though: it persists the state of the owner side of the association (the one which doesn't have a mappedBy
attribute)
这篇关于级联的ManyToMany只能以一种方式级联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!