Skip to content

How to cascade delete set of enums in JPA?

I have the roles field in User entity:

@Table(indexes = {
        @Index(columnList = "uuid")
public class User


   @ElementCollection(fetch = FetchType.EAGER)
   private Set<Roles> roles;

when I try to delete user with a query, the referential integrity constraint violation occurs, because user is referenced from User_roles table.

How to solve this in any way?

DDL for related table shows

create or replace table User_roles
    User_id bigint not null,
    roles varchar(255) null,
    constraint FKi81fp6mx433heb7dvbxqaqvpv
        foreign key (User_id) references User (id)

i.e. it doesn’t contain ON DELETE CASCADE clause. I need it be there.


You can add ON DELETE CASCADE clause to the FOREIGN KEY constraint in the following way:

import javax.persistence.ForeignKey;

@Table(name ="User")
public class User
      name = "User_roles",
      joinColumns = @JoinColumn(name = "User_id"),
      foreignKey = @ForeignKey(
         name = "user_fk",
         foreignKeyDefinition = "FOREIGN KEY (User_id) REFERENCES User(id) ON DELETE CASCADE")
   private Set<Roles> roles;