使用@ElementCollection 对实体进行级联删除

Cascade delete on entity with @ElementCollection

我在级联删除我的 Parent 实体时遇到问题:

org.postgresql.util.PSQLException: table 上的更新或删除 "child" 违反约束 "XXX": 对于键 (id)=(4) [=28= 中有引用] "child_properties"

@Entity
@Table(name = "Parent")
public class Parent{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToMany(fetch = FetchType.EAGER,mappedBy = "parent")
    @OnDelete(action = OnDeleteAction.CASCADE)
    private Set<Child> children;
}

@Entity
@Table(name = "child")
public class Child{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "parent_id")
    private Parent parent;

    @ElementCollection(fetch = FetchType.EAGER)
    private Map<String,String> properties;
}

我希望 child 在 parentRepository.delete(parent) 上删除它的属性 但这只发生在 childRepository.delete(child)。 parent 删除抛出异常

解决方案是 ~3 小时谷歌搜索... 这个想法是设置自定义外键

@ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(name = "child_properties"
        ,joinColumns = {
            @JoinColumn(name = "child_id"
                , referencedColumnName = "id"
                ,foreignKey=@ForeignKey(name="CHILD_PROPERTY_FK"
                    , foreignKeyDefinition = "FOREIGN KEY (child_id) references public.child (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE CASCADE"))
        }
    )
    @MapKeyColumn(name = "name")
    @Column(name = "value")
    private Map<String,String> properties;