0

I am trying to delete one object from my project. It is dependent on many other classes. I understand that I need to free that object from all other dependencies. I tried to delete all its dependencies but still I am getting the Foreign key constraint error

Here are my classes

class LabAssistant{
    // variables
    @OneToMany(cascadeType.All,
               orphanRemoval=true,
               mappedBy="labAssistant")
    private List<LabRecord> labRecords;
    
    //Getters and setters
}


class LabRecord {
    //variables
    @OneToMany(cascade = CascadeType.ALL, mappedBy="labRecord")
    private List<Test> tests;

    @ManyToOne
    @JoinColumn(name = "lab_id")
    private LabAssistant labAssistant;

    //Getters and Setters
}

class Test{
    @Lob
    private byte[] testReport;

    @ManyToOne
    @JoinColumn(name = "lab_record_id")
    private LabRecord labRecord;

    @ManyToOne
    @JoinColumn(name = "test_info_id")
    private TestInfo testInfo;

    //Getters and setters
}

boolean deleteAssistant(int id){
  LabAssistant labAssistant = session.load(LabAssistant.class, id);
  for(LabRecord l : labAssistant.getLabRecords()){
    for(Test t: l.getTests()){
      t.setTestInfo(null);
    }
    l.getTests().clear();
  }
}
labAssistant.getLabRecords().clear();
session.delete(labAssistant);
return true;
}

I am still getting foreign key constraint error

'db'.'tests', Constraint 'fkey' Foreign Key ('lab_record_id') References 'lab_records'('id')

Any help appreciated!!

4

2 回答 2

0

不知何故,重新创建数据库解决了这个问题。

于 2020-12-16T05:48:16.400 回答
0

当建立 LabAssistant 和 LabRecord 之间的关系为 CascadeType.ALL 和 orphanRemoval = true 时,分配给 LabAssistant 的 LabRecord 也将被消除,大概您有与这些 LabRecord 之一相关的测试条目,请阅读以下内容:

https://www.objectdb.com/java/jpa/persistence/delete

于 2020-11-25T11:18:20.713 回答