Urbanleg
Urbanleg

Reputation: 6532

ManyToMany with cascade all only cascading one way

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

Upvotes: 0

Views: 443

Answers (1)

JB Nizet
JB Nizet

Reputation: 691645

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)

Upvotes: 1

Related Questions