spring数据:管理双向多对多关系

jecbmhm3  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(375)

我有一个双向多对多的关系 Role 以及 Scope . 创造这两个实体,甚至他们的孩子的帮助下 CascadeType.PERSIST 简单明了。
这个 Role 实体简化为:

@Entity
@Table(uniqueConstraints = @UniqueConstraint(name = "role_name", columnNames = "name"))
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String name;

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST, mappedBy = "roles")
    private Set<Scope> scopes;

}

以及 Scope :

@Entity
@Table(uniqueConstraints = @UniqueConstraint(name = "scope_name", columnNames = "name"))
public class Scope {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String name;

    @JoinTable(name = "role_scopes", joinColumns = @JoinColumn(name = "scope_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
    @ManyToMany(cascade = CascadeType.REMOVE)
    private Set<Role> roles;

}

它们的存储库很简单 CrudRepository 扩展名:

public interface RoleRepository extends CrudRepository<Role, Long> {}
public interface ScopeRepository extends CrudRepository<Scope, Long> {}

以下代码段举例说明了实体插入:

Role adminRole = roleRepository.save(new Role("ADMIN"));
Scope allReadScope = scopeRepository.save(new Scope("all.read"));
Scope allWriteScope = scopeRepository.save(new Scope("all.write"));
``` `Role` 以及 `Scope` 在 `CascadeType.PERSIST` ,如下所示:

Role managedRole = roleRepository.save(new Role("ADMIN", new Scope("all.read"), new Scope("all.write")));

然而。。。更新 `managedRole` 导致 `org.hibernate.PersistentObjectException: detached entity passed to persist` 例外情况:

managedRole.getScopes().remove(allReadScope);
roleRepository.save(managedRole); // PersistentObjectException!

我试着修改 `Role::scopes` 的 `CascadeType` 也包括 `DETACH` ,  `MERGE` 和/或 `REFRESH` 没有成功。我们该怎么办?
41ik7eoe

41ik7eoe1#

很可能您会面临这个问题,因为在双向Map中您没有维护关系的双方。让我们说进来 Role :

void add(Scope scope) {
   this.scopes.add(scope);
   scope.getRoles().add(this);
}

老实说,我会完全放弃双向Map。保持这种状态真是一场噩梦。

相关问题