How to cascade delete set of enums in JPA?



I have the roles field in User entity:

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

   ...

   @ElementCollection(fetch = FetchType.EAGER)
   @Enumerated(EnumType.STRING)
   @NotEmpty
   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.

Answer

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

import javax.persistence.ForeignKey;

@Entity
@Table(name ="User")
public class User
{
   @ElementCollection
   @CollectionTable(
      name = "User_roles",
      joinColumns = @JoinColumn(name = "User_id"),
      foreignKey = @ForeignKey(
         name = "user_fk",
         foreignKeyDefinition = "FOREIGN KEY (User_id) REFERENCES User(id) ON DELETE CASCADE")
   )
   @Enumerated(EnumType.STRING)
   private Set<Roles> roles;
}


Source: stackoverflow