首页 > 解决方案 > 使用@ElementCollection 对实体进行级联删除

问题描述

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

org.postgresql.util.PSQLException:表“child”上的 UPDATE 或 DELETE 违反约束“XXX”:对于键 (id)=(4),表“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;
}

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

标签: javajpahibernate-cascade

解决方案


解决方案是大约 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;

推荐阅读