0

I have problem with deleting from database childs from OneToMany relationship.

Here are my classses:

public class Question {

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

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

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

And Answer class:

public class Answer {

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

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

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

And I'am trying to remove question and all its answers like this:

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);
    }
  }

And I'm getting:

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

I have no idea what is wrong. When I put CascadeType.ALL on Question getAnswers() i still get the same problem. I am using Hibernate ORM with Spring Data. Also when I force app to show sql commands, I can see that Hibernate isn't even trying to remove Answers, there is only one delete - on question.

Laurentiu L.
  • 6,566
  • 1
  • 34
  • 60
Bouncer00
  • 123
  • 1
  • 4
  • 12

1 Answers1

0

Try cascade, use like below

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

this link your answer JPA CascadeType.ALL does not delete orphans

Community
  • 1
  • 1
Ömer Faruk Kurt
  • 500
  • 3
  • 14
  • Still same result, CascadeType.ALL, and clean, rebuild project as suggested in link. – Bouncer00 Aug 11 '15 at 10:25
  • From link: If you are using it with Hibernate, you'll have to **explicitly** define the annotation `CascadeType.DELETE_ORPHAN`, which can be used in **conjunction** with JPA `CascadeType.ALL`. – Naman Gala Aug 11 '15 at 10:31