简体   繁体   中英

Cascade delete on entity with @ElementCollection

I have a problem when cascade deleting my Parent entity:

org.postgresql.util.PSQLException: UPDATE or DELETE on table "child" violates constraint "XXX": for key (id)=(4) there are references in table "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;
}

I expected child to delete its properties on parentRepository.delete(parent) but this only happens on childRepository.delete(child). parent delete throws exception

the solution was ~3 hours googling... the idea is to set custom foreign key

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM