Arnold Robert Turdean
Arnold Robert Turdean

Reputation: 294

Spring Boot Cross Entity Reference Validation

As usually I also have multiple entities in my MongoDB database. These entities are referring to each other by identifiers.

Example: An evaluation entity may refer to a Patient entity. Actually when I'm saving any entity I'm validating all these reference. So when I save an evaluation I will check if the referred patient is still exists. If not then the save will fail.

The problem with this attitude is that if I delete a patient the evaluation service should process it and update the evaluation as well, but what happens if the patient was deleted correctly but the evaluation's business logic failed hence the old patientId remained in it. After this happening nobody will be able to do anything with the evaluation itself because the server will fail to save any change with the evaluation because of a missing cross reference to a patient.

Hence it seems that my validation layer is too strict, but is it better to simply not validate this kind of cross references ? So the question is that should I validate the Patient's existence when saving the Evaluation entity ? (I mean should I validate it every single time when I save it)

I'm very curious about you point of view for this kind of problem. Thank you so much for any comment under the question, Have a nice day :)

Upvotes: 0

Views: 147

Answers (1)

Valijon
Valijon

Reputation: 13113

You need to remove all entities associated to the Patient id (before deletion), since any other entity cannot point to non-existing patient entity.

Other solution: Logical erase. Do not remove patient entity, just deactivate it. This way, your already-saved entities can point to Patient entity, but if you want save them again, your validation service will fail saying: "Patient Id is deactivated".

Upvotes: 1

Related Questions