JPA删除没有级联到FK并且没有报告错误

时间:2017-12-21 06:12:04

标签: java jpa foreign-keys cascade many-to-one

我有2个简单表问题(父表)和答案(子),其中问题有1:许多答案实现为:

public class Answer {
    ....
        @JsonBackReference
        @ManyToOne
        @JoinColumn(name="questionId")
        private Question question;

public class Question{
...
   @JsonManagedReference
   @OneToMany(mappedBy="question", fetch=FetchType.EAGER, orphanRemoval = true, cascade=CascadeType.ALL)
   private Set<Answer> answer;

mysql数据库已建立PK / FK,并且当尝试在SQL中删除失败(如预期)时,如果我尝试从Question中删除(数据库中没有级联),如下面的测试所证明的那样在SQL中:

mysql> delete from question where id = 3;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`quizdb`.`answer`, CONSTRAINT `answer_ibfk_1` FOREIGN KEY (`questionId`) REFERENCES `question` (`id`))

我的代码试图删除问题和答案:

public boolean deleteQuestion(int qid) {
    boolean status = false;

    Question question = em.find(Question.class, qid);
    System.out.println("Question to go: " + question);
    try {
        em.remove(question);
        em.flush();   // added per comment, but still broken
    }catch(Exception e) {
        e.printStackTrace();
    }
    question = em.find(Question.class, qid); 
    System.out.println("question found? " + question);
    return question == null;

在第二次查找尝试时,它会在控制台中找到问题,没有错误或消息,它指出:&#34;发现问题? null&#34;,正如人们所期望的那样,该方法返回True,但问题行仍然存在于表中,并且没有级联到子回答。任何线索都表示赞赏。

0 个答案:

没有答案