I have three Entities: User, Role and Authority.
User has ManyToMany bi-directional mapping to Role and uni-directional ManyToMany mapping to Authority:
Code:
@Entity
public class User {
@ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}, fetch = FetchType.EAGER)
@JoinTable(name = "user_authority",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "authority_id"))
private Set<Authority> authorities = new HashSet<>();
@ManyToMany(mappedBy = "users", cascade = {CascadeType.DETACH, CascadeType.REFRESH}, fetch = FetchType.EAGER)
private Set<Role> roles = new HashSet<>();
//other stuff
}
@Entity
public class Role {
@ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}, fetch = FetchType.EAGER)
@JoinTable(name = "user_role",
joinColumns = @JoinColumn(name = "role_id"),
inverseJoinColumns = @JoinColumn(name = "user_id"))
private Set<User> users = new HashSet<>();
//other stuff
}
@Entity
public class Authority {
//other stuff
}
and now when I run these tests:
Code:
@Test
public void shouldAddNewRoleToExistingUser() {
//given
final User user = userRepository.findOne(userRepository.save(createRandomUser()).getId());
final Role role = roleRepository.save(createRandomRole());
//when
User changedUser = userRepository.findOne(userService.changeRole(user, role).getId());
//then
assertThat(changedUser)
.isNotNull();
assertThat(changedUser.getRoles())
.containsExactly(role);
}
@Test
public void shouldAddNewAuthorityToExistingUser() {
//given
final User user = userRepository.findOne(userRepository.save(createRandomUser()).getId());
final Authority authority = authorityRepository.save(createRandomAuthority());
//when
User changedUser = userRepository.findOne(userService.changeAuthority(user, authority).getId());
//then
assertThat(changedUser)
.isNotNull();
assertThat(changedUser.getAuthorities())
.containsExactly(authority);
}
//change authority/role looks like this:
public User changeRole(final User user, final Role role) {
if (user.hasRole(role)) {
user.removeRole(role);
} else {
user.addRole(role);
}
return repository.save(user);
}
The "Authority test" passes, but "Role test" fails (change is not being persisted - User still has no Roles, although it has Authority)!
Can you please help me to answer why??
Thank you in advance