There is a unidirectional ManyToMany
mapping between Role
and Privilege
with Role
as the owning entity like so
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() {
}
}
Whenever i set updated list of privileges in a role and update, the join table is successfully updated without removing either target or owning entity, and that is desired result. The problem is on update it also affect another self join table in Privilege
called privilege_hierachy
which is not what is expect.
Is it possible for hibernate to only update the Role
-Privilege
mant-to-many relationship and let other relation unchanged.
Spring Data Jpa is used for data persistence
It sounds like you are updating the privileges by (removing old privileges and) adding new ones. If you do that, clearly, the second join table (the self-referencing table) could be updated with new rows, based on what you are passing.
I see that for the self-referencing table, Privilege, you are not setting cascade type. It defaults to no operation, and that sounds like what you want. But my guess is based on what you said "Whenever i set updated list of privileges in a role", and that tells me you are creating new privileges for a role, instead of using existing privileges and associate them with the role.