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;