与@OneToMany关系抛出的“ConstraintViolationException:无法删除或更新父行”

时间:2014-02-10 07:54:49

标签: hibernate jpa jpa-2.0 spring-data-jpa

我有如下的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`))

我的问题如下:

  1. 如果我想保留联接表即curriculum_work_experiences,我该如何正确删除WorkExperience?
  2. 我注意到通过在MySql中手动将fk设置为on cascade delete,它运行正常,但我不确定实现我手​​动完成所需的JPA注释是什么......

1 个答案:

答案 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;
        ...