删除OneToMany关系的子女无法正常工作

时间:2015-08-11 10:02:30

标签: java hibernate orm spring-data

我从OneToMany关系中删除数据库子项时遇到问题。

以下是我的课程:

public class Question {

 private Set<Answer> answers
/.................

  @OneToMany(fetch = FetchType.EAGER, mappedBy = "question", orphanRemoval = true)
  public Set<Answer> getAnswers() {
    return this.answers;
  }

/.................
}

答案课:

public class Answer {

private Question question
/............

  @ManyToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "QUESTION_ID", nullable = false)
  public Question getQuestion() {
    return this.question;
  }

/...........
}

我正试图删除问题及其所有答案:

public void deleteQuestions(List<Question> questions){

    for(Question question : questions){
      Question databaseQuestion = questionRepository.findOne(question.getId());
      for(Answer answer : databaseQuestion.getAnswers()){
        answerRepository.delete(answer.getId());
      }
      questionRepository.delete(databaseQuestion);
    }
  }

我得到了:

ORA-02292: integrity constraint (DATABASE_NAME.ANSWER_QUESTION_FK) violated - child record found

我不知道出了什么问题。 当我CascadeType.ALL Question getAnswers()时,我仍然遇到同样的问题。 我正在使用Hibernate ORM和Spring Data。 此外,当我强制app显示sql命令时,我可以看到Hibernate甚至没有尝试删除Answers,只有一个删除 - 问题。

1 个答案:

答案 0 :(得分:0)

尝试级联,使用如下

@OneToMany (cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "question",orphanRemoval=true)

此链接您的答案 JPA CascadeType.ALL does not delete orphans