1

I have a permission entity relation where one user can have multiple permission. When I try to update a blank set to the user the update is not taking place.

My entities

@Entity
public class Users {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String clientId;

    private String userName;

    private String userStatus;

    @ManyToOne(cascade = {CascadeType.MERGE, CascadeType.PERSIST}, fetch = FetchType.EAGER)
    private Users parentUserId;

    @Builder.Default
    @OneToMany(mappedBy = "parentUserId", fetch = FetchType.EAGER)
    private Set<Users> children = new HashSet<>();

    @OneToMany(mappedBy = "user", cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
    @Builder.Default
    private Set<AccessMapping> permissions = new HashSet<>();

    private Long updatedAt;
}



@Entity
public class AccessMapping {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinTable(name = "FeatureGroupPermissions",
    joinColumns = @JoinColumn(name = "FeatureGroupId"),
    inverseJoinColumns = @JoinColumn(name = "PermissionId"))
    private FeatureGroups featureGroup;

    @ManyToOne
    @JoinTable(name = "UserPermissions",
    joinColumns = @JoinColumn(name = "UserId"),
    inverseJoinColumns = @JoinColumn(name = "PermissionId"))
    private Users user;

    private String accessType;

    private Long updatedAt;
}

One user has permission to multiple feature groups.

The size of permission hashSet is equivalent to the number of permissions a user have. If i want to remove all permission of the user i'm setting a blank hashSet and updating the user using EntityManager.merge() function. But this is not working. The permissions still remain and when i fetch user the hashSet is still of the original length meaning that no permissions were removed.

What am I doing wrong or not understanding about hibernate entities?

Thanks in advance.

Belphegor21
  • 454
  • 1
  • 5
  • 24

1 Answers1

1

You need add the orphanremoval=true in your code.

@OneToMany(mappedBy = "user", cascade = {CascadeType.ALL}, orphanRemoval = true, fetch = FetchType.EAGER)

For detail, you can ref this link:

JPA 2.0 orphanRemoval=true VS on delete Cascade

And also, it looks strange that your jointable setting, it should like this (The first column is the owning side):

@JoinTable(name = "UserPermissions",
        joinColumns = @JoinColumn(name = "PermissionId"),
        inverseJoinColumns = @JoinColumn(name = "UserId"))
Tim
  • 2,006
  • 2
  • 18
  • 25