Unable to remove foreign key constraint in hibernate

527 views Asked by At

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

2

There are 2 answers

0
Jon B On BEST ANSWER

Somehow recreating the database solved the problem.

0
JLazar0 On

When establishing the relationship between LabAssistant and LabRecord as CascadeType.ALL and orphanRemoval = true, LabRecord that are assigned to LabAssistant will also be eliminated, presumably you have Test entries related to one of these LabRecord, read this:

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