Hibernate单向ManyToMany更新目标组件关系

时间:2017-02-21 20:27:12

标签: java hibernate orm many-to-many spring-data-jpa

ManyToManyRole之间存在单向Privilege映射,Role作为拥有实体,如此

Role

@Entity
public class Role extends BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "role_id")
    private Integer roleId;
    @Size(max = 45)
    @Column(name = "role")
    private String role;

    @JoinTable(name = "role_privilege", joinColumns = {
            @JoinColumn(name = "role_role_id", referencedColumnName = "role_id")}, inverseJoinColumns = {
            @JoinColumn(name = "privilege_privilege_id", referencedColumnName = "privilege_id")})
    @ManyToMany(
            cascade = {
                CascadeType.DETACH,
                CascadeType.MERGE,
                CascadeType.REFRESH,
                CascadeType.PERSIST }, fetch = FetchType.EAGER, targetEntity = Privilege.class)
    private Collection<Privilege> privilegeCollection;

    @Transient
    private Collection<Privilege> parentPrivilegeCollection;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "roleId")
    @JsonIgnore
    private Collection<User> userCollection;

    public Role() {
    }
    //getters,setter,hashcode,equals removed for brevity
}

Privilege

@Entity
public class Privilege extends BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "privilege_id")
    private Integer privilegeId;
    @Size(max = 45)
    @Column(name = "name")
    private String name;
    @Size(max = 150)
    @Column(name = "description")
    private String description;
    @Size(max = 45)
    @Column(name = "friendly_name")
    private String friendlyName;
    @JoinTable(name = "privilege_hierachy", joinColumns = {
            @JoinColumn(name = "parent_privilege", referencedColumnName = "privilege_id")}, inverseJoinColumns = {
            @JoinColumn(name = "child_privilege", referencedColumnName = "privilege_id")})
    @ManyToMany
    private Collection<Privilege> privilegeCollection;

    public Privilege() {
    }
}

问题

每当我在角色和更新中设置更新的权限列表时,连接表都会成功更新,而无需删除目标或拥有实体,这是所需的结果。问题是在更新时它还影响Privilege中名为privilege_hierachy的另一个自联接表,这不是预期的。

hibernate是否有可能只更新Role - Privilege mant-to-many关系并让其他关系保持不变。

Spring Data Jpa用于数据持久性

1 个答案:

答案 0 :(得分:1)

听起来您正在通过(删除旧权限)添加新权限来更新权限。如果你这样做,很明显,第二个连接表(自引用表)可以根据你传递的内容用新行更新。

我看到对于自引用表Privilege,您没有设置级联类型。它默认为无操作,这听起来像你想要的。但我的猜测是基于你所说的“每当我在角色中设置更新的权限列表”时,它告诉我你正在为一个角色创建新的权限,而不是使用现有的权限并将它们关联起来与角色。