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

Jon B
  • 71
  • 1
  • 7
  • You could try like this: for (Test test : labRecord.tests) { test.labRecord = null; } testRepository.saveAll(labRecords.tests); labRecordRepository.remove(labRecord); – Thomas Nov 25 '20 at 11:10
  • You don't clear your getLabRecords collection in labAssistant, because you must delete labAssistnat and its sons. – Joe Taras Nov 25 '20 at 11:22
  • I tried using labAssistant.setLabRecords(null); but its still now working – Jon B Nov 25 '20 at 11:31

2 Answers2

0

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

JLazar0
  • 1,257
  • 1
  • 11
  • 22
0

Somehow recreating the database solved the problem.

Jon B
  • 71
  • 1
  • 7