【问题标题】:Deleting children of OneToMany relationship not working删除 OneToMany 关系的孩子不起作用
【发布时间】:2015-11-03 12:02:05
【问题描述】:

我在从 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() 上时,我仍然遇到同样的问题。 我正在使用带有 Spring Data 的 Hibernate ORM。 此外,当我强制应用程序显示 sql 命令时,我可以看到 Hibernate 甚至没有尝试删除答案,只有一个删除 - 问题。

【问题讨论】:

  • 它可能没有执行循环答案!尝试调试您的代码。
  • 您是否尝试过描述一个 cascadeType?
  • 我敢肯定,for循环执行后,这个问题只有一个答案。
  • 好的。您可以尝试按 ID 删除问题吗?
  • 当我按 ID 删除问题时,仍然是同样的问题。

标签: java hibernate orm spring-data


【解决方案1】:

尝试级联,如下使用

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

这个链接你的答案 JPA CascadeType.ALL does not delete orphans

【讨论】:

  • 仍然是相同的结果,CascadeType.ALL,并按照链接中的建议清理、重建项目。
  • 来自链接:如果你在 Hibernate 中使用它,你必须显式定义注解CascadeType.DELETE_ORPHAN,它可以在连词中使用 b> 与 JPA CascadeType.ALL.
猜你喜欢
  • 2017-06-23
  • 2015-05-05
  • 2011-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-03
  • 2022-08-13
  • 2014-08-02
  • 2012-01-08
相关资源
最近更新 更多