Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Many-Many relationship with cascade delete

Tags:

hibernate

jpa

I have a requirement to implement role-right based authentication. The scenario is like,

A role has multiple/many rights. In opposite, A right can be assigned to multiple role(s).

So, here team has designed three tables names as,

1) Role (Columns: roleId,name,desc)

2) Right (Columns : rightId,name,desc)

3) RoleRightAssociation (Columns : roleId,rightId,assignedDate,assignedBy)

The third table is storing the data like,

Right 'A' was assigned to Role 'B' by the user 'X' on a particular date.

UseCase is, When I delete a Role all the entries from RoleRightAssociation corresponding to that Role must be deleted (Delete Cascade). But Not from a Right table.

I've created three entities for this and given the relations like, Role:

 @OneToMany(mappedBy="roleRoghtId.roleId",cascade=CascadeType.ALL)
  private List<RoleRight> roleRightsList=new ArrayList<RoleRight>();

Right:

@OneToMany(mappedBy="roleRoghtId.rightId",cascade=CascadeType.ALL)
   private List<RoleRight> roleRightsList;

RoleRightAssociation:

     @Entity
     @Table(name = "RoleRight")
     @AssociationOverrides({ 
     @AssociationOverride(name = "roleRoghtId.roleId",joinColumns = @JoinColumn(name = "roleId")),
     @AssociationOverride(name = "roleRoghtId.rightId",joinColumns = @JoinColumn(name = "rightId")) })
public class RoleRightAssociation {
...
   @EmbeddedId
    private PrimaryKeyRoleRight roleRoghtId=new PrimaryKeyRoleRight();

...
}

PrimaryKeyRoleRight :

 @ManyToOne(cascade = CascadeType.ALL)
    private Role roleId;

    @ManyToOne(cascade = CascadeType.ALL)
    private Right rightId;

I am not able to satisfy the given use case. What relations do I need to apply in respected JPA entities?

Thanks in Advance.

like image 438
Chirag Soni Avatar asked Jan 25 '26 10:01

Chirag Soni


1 Answers

Cascade.ALL does not include delete Orphan.

You have to add orphanRemoval = true to your roleRightsList in Role entity

like image 190
Gab Avatar answered Jan 28 '26 03:01

Gab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!