我尝试从多对多关系中删除实体,但是在我的存储库保存父实体后,没有任何反应。
用户存储库:
public interface UserRepository extends EntityGraphJpaRepository<User, Long> {
User findByEmailIgnoreCase(String email);
Page<User> findBy(Pageable pageable);
User findByEmail(String name, com.cosium.spring.data.jpa.entity.graph.domain.EntityGraph entityGraph);
}
抽象实体
@MappedSuperclass
public abstract class AbstractEntity implements Serializable {
private static final long serialVersionUID = -2523912452050488728L;
@Id
@GeneratedValue
private Long id;
@Version
private int version;
public Long getId() {
return id;
}
public int getVersion() {
return version;
}
@Override
public int hashCode() {
if (id == null) {
return super.hashCode();
}
return 31 + id.hashCode();
}
@Override
public boolean equals(Object other) {
if (id == null) {
// New entities are only equal if the instance if the same
return super.equals(other);
}
if (this == other) {
return true;
}
if (!(other instanceof AbstractEntity)) {
return false;
}
boolean test = id.equals(((AbstractEntity) other).id);
return id.equals(((AbstractEntity) other).id);
}
}
用户实体
@NamedEntityGraphs(value = {
@NamedEntityGraph(name = "User.roles.groups", attributeNodes = {
@NamedAttributeNode("roles"),
@NamedAttributeNode("groups")
})
})
@Entity(name="userInfo")
public class User extends AbstractEntity {
@ManyToMany(mappedBy = "users", fetch = FetchType.LAZY, cascade= {CascadeType.PERSIST, CascadeType.MERGE}) //inverse side
private Set<Role> roles = new HashSet<Role>();
public void addRole(Role role) {
this.roles.add(role);
role.getUsers().add(this);
}
public void removeRole(Role role) {
this.roles.remove(role);
role.getUsers().remove(this);
}
//...
}
角色实体:
public class Role extends AbstractEntity {
@ManyToMany(fetch = FetchType.LAZY, cascade= {CascadeType.PERSIST,CascadeType.MERGE}) //owning side
@JoinTable(
name = "role_user",
joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"))
private Set<User> users = new HashSet<User>();
用户服务:
@Service
public class UserService implements CrudEntityServiceInterface{
private UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public void save(User user) {
this.userRepository.saveAndFlush(user);
}
public User updateRolesForUser(User user,Set<Role> roleItems,RoleService roleService) {
Set<Role> rolesToRemove = new HashSet<Role>();
for(Role oldRole: user.getRoles()) {
//remove roles which are deselected
if(!roleItems.contains(oldRole)) {
Optional<Role> oldRoleLoaded = (roleService.getRepository()).findById(oldRole.getId(),EntityGraphs.named("Role.users.groups"));
rolesToRemove.add(oldRoleLoaded.get());
}
}
rolesToRemove.forEach(x -> user.removeRole(x));
//added selected roles
roleItems.forEach(x -> {
Optional<Role> xLoaded = (roleService.getRepository()).findById(x.getId(),EntityGraphs.named("Role.users.groups"));
user.addRole(xLoaded.get());
} );
return user;
}
//...
}
在我的控制器中,我调用类似的东西
user = userService.updateRolesForUser(user,roles,roleService);
userService.save(user);
我必须使用entityGraph,因为我不想使用Fetch.Eager。
您是否知道为什么我无法从用户中删除角色?我也尝试了Cascade.Remove - 但这并不能解决问题,而且是不好的做法,我猜。
编辑:当我打电话时
rolesToRemove.forEach(x -> {user.removeRole(x); roleService.save(x);});
我要从关系中删除的实体将被删除。但我认为用户的所有内容都是通过 CascadeType.Persist 在用户存储库上调用保存来更新的?为什么我还要调用"保存"角色?
老问题,但角色控制多对多关系。如果要保留对关系的更改,则必须更新角色对象,而不是用户端。