如何解决Spring Data JPA:级联多对多关系的问题
我在 Role
和 Scope
之间存在多对多关系。为了能够在 Role 上使用 CascadeType.REMOVE
,我将其设为双向。
@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;
}
@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
被删除时,它的删除必须级联到所有与 Scope 有关系的表中,例如:scopeRepository.deleteById(someId)
也应该从role_scopes
表中删除记录. (工作) -
Scope
必须通过scopeRepository.save(scope)
和通过Role
持久化,如果此角色尚未与此范围相关,例如:roleRepository.save(role.withScopes(scope1,scope2).build())
。如果scope1
不存在,则创建一个scope
和一个role_scopes
值。如果scope2
确实存在但与角色没有任何关系,则仅生成一个role_scopes
值。 (不工作)
可以使用 Scope
通过 Role
创建全新的 CascadeType.PERSIST
,但如果该范围已经存在,则会引发 detached entity passed to persist
错误,但我希望 Hibernate 简单地忽略 Scope 创建(在本例中)并检查是否还有 role_scopes
记录,如果没有则创建一个,否则也忽略它(甚至不更新值)。
考虑以下片段:
Scope scope1 = new Scope("foo");
Scope scope2 = new Scope("bar");
Role role1 = Role.builder("foobar").withScopes(scope1,scope2).build();
roleRepository.save(role1);
场景 1) scope
、role
和 role_scopes
表为空:
should create role1,scope1 and scope2 and their relationships (role1 vs scope1 and role1 vs scope2) on role_scopes table
场景 2)role
表为空,scope1
和 scope2
存在但不与任何角色相关(空 role_scopes
表):
should create role1 and it's relationships (role1 vs scope1 and role1 vs scope2) on role_scopes table
场景3)role
表为空,scope1
存在且与role1
相关(role_scopes
不为空)且scope2
不存在:
should create role1,scope2 and their relationship (role1 vs scope2) on role_scopes table
场景 4) role1
、scope1
和 scope2
存在并且都与 role1
相关:
do nothing
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。