0
votes

Project on github

I have 3 entities that are connected via each other like this:

Quiz

@ManyToOne()
private Quiz quiz;

@ManyToOne()
private QuizQuestions question;

I'm trying to delete a quiz using quizId but I am getting:

Cannot delete or update a parent row: a foreign key constraint fails (bananpiren.quizquestions, CONSTRAINT FK_QUIZQUESTIONS_QUIZ_QUIZID FOREIGN KEY (QUIZ_QUIZID) REFERENCES quiz (QUIZID)) Error Code: 1451

My guess is that JPA doesn't like the foreignkey and works differently from @OneToMany behavior and Cascading doesn't seem to work.

I've tried @ManyToOne

  • CascadeType.REMOVE
  • CascadeType.Persist

What I want to happen is that when a user deletes a Quiz, all the connected questions and answers should be deleted aswell. Is this possible using only JPA and in a @ManyToOne relationship? If possible how?

1

1 Answers

1
votes

The problem is, you want to cascade on the @OneToMany relations, not the @ManyToOne relations. Cascading on the @ManyToOne relations would mean removing a quiz when you're removing an answer to it. So, you will need to define the corresponding @OneToMany variables on the Quiz class and do cascade = CascadeType.REMOVE there in order to achieve the desired effect.