How can I fix foreign key constraint violation when using Spring Data @OneToMany relationship with @JoinTable?
Models:
@Entity
@Data
public class Email {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "email_seq")
@SequenceGenerator(name = "email_seq", sequenceName = "email_seq")
private Long id;
@NotNull
private String title;
@OneToMany
@JoinTable(
name = "email_attachment",
joinColumns = @JoinColumn(name = "EMAIL_ID"),
inverseJoinColumns = @JoinColumn(name = "ATTACHMENT_ID")
)
private List<Attachment> attachments;
...
}
@Entity
@Data
public class Attachment {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "attachment_generator")
@SequenceGenerator(name = "attachment_generator", sequenceName = "attachment_seq")
private Long id;
...
}
When I try to delete Attachment like this:
attachmentRepository.delete(id)
it throws following error:
ERROR: update or delete on table "attachment" violates foreign key constraint "email_attachment_attachment_id_fkey" on table "email_attachment" Details: Key (id)=(6) is still referenced from table "email_attachment".
OneToMany(cascade = CascadeType.REMOVE)doesn't help. - ZiemEmail- user3973283