ManyToMany with cascade all only cascading one way

你离开我真会死。 提交于 2019-12-25 09:12:09

问题


I have 2 entities: 1) User 2) Department.

each contains a SET of the other since the relationship between them is manyToMany,

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.

is called implicitly.

BUT , when i do

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?

thanks


回答1:


The cascade is irrelevant to what you're doing. Cascading means: when I save X, also save Y.

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.

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)



来源:https://stackoverflow.com/questions/18233258/manytomany-with-cascade-all-only-cascading-one-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!