无法在hibernate中删除外键约束

kkbh8khc  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(499)

我正试图从我的项目中删除一个对象。它依赖于许多其他类。我知道我需要将该对象从所有其他依赖项中释放出来。我试图删除它的所有依赖项,但仍然得到外键约束错误
这是我的课

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

我仍然得到外键约束错误

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

感谢您的帮助!!

r8uurelv

r8uurelv1#

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

r1zhe5dt

r1zhe5dt2#

当将labassistant和labrecord之间的关系建立为cascadetype.all和orphanremoval=true时,分配给labassistant的labrecord也将被消除,可能您有与这些labrecord之一相关的测试条目,请阅读以下内容:
https://www.objectdb.com/java/jpa/persistence/delete

相关问题