我有如下的OneToMany关系:
@Entity
public class Curriculum {
@OneToMany(cascade = CascadeType.ALL)
private Set<WorkExperience> workExperiences;
...
这是WorkExperience实体:
@Entity
public class WorkExperience {
...
当我尝试按如下方式删除WorkExperience时:
@Override
public void deleteWorkExperience(long workExperienceId) {
workExperienceRepository.delete(workExperienceId);
}
我得到以下异常:
org.hibernate.exception.ConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`bignibou`.`curriculum_work_experiences`, CONSTRAINT `FKFA6D4B9F8B68AA0C` FOREIGN KEY (`work_experiences`) REFERENCES `work_experience` (`id`))
我的问题如下:
curriculum_work_experiences
,我该如何正确删除WorkExperience?on cascade delete
,它运行正常,但我不确定实现我手动完成所需的JPA注释是什么...... 答案 0 :(得分:-1)
Orphan Removal是这种情况下的方法。你不能通过使用workExperienceId直接删除它导致它的单向连接表关系,并且数据库受外键参照完整性约束,你必须使用Curriculum实体删除它,你需要获得对set workExperiences的引用和从该集合中删除它,但首先确保将orpanRemoval = true元素添加到@OneToMany注释中,如下所示,此属性强制同时删除连接表中的任何引用。
@Entity
public class Curriculum {
@OneToMany(cascade = CascadeType.ALL, orphanRemoval=true)
private Set<WorkExperience> workExperiences;
...