如何级联删除 JPA 中的枚举集?

How to cascade delete set of enums in JPA?

我在 User 实体中有 roles 字段:

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

   ...

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

当我尝试使用查询删除用户时,发生参照完整性约束冲突,因为用户是从 User_roles table.

引用的

如何解决这个问题?


DDL 相关 table 节目

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

即它不包含 ON DELETE CASCADE 子句。我需要它在那里。

您可以通过以下方式将 ON DELETE CASCADE 子句添加到 FOREIGN KEY 约束:

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;
}