spring数据jpa:级联多个关系的问题

nzrxty8p  于 2021-06-29  发布在  Java
关注(0)|答案(0)|浏览(217)

我和他之间有很多关系 Role 以及 Scope . 为了能使用 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 如果已删除,则必须将其删除级联到与作用域有关系的所有表中,例如: scopeRepository.deleteById(someId) 也应该从 role_scopes table((正在工作) 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忽略作用域的创建(在本例中),并检查是否还有 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

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题