Search code examples
javaspringhibernatejpahibernate-jpa

Unable to remove foreign key constraint in hibernate


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!!


Solution

  • Somehow recreating the database solved the problem.