java - Hibernate cascading multiple layers -
let's assume have following medical situation:
3 entities: consultation, 1 nullable prescription. prescription set of medicines.
i've modelled them follows: (java code stripped of unnecessary info)
consultation { @id @generatedvalue(strategy = generationtype.identity) private long id; @onetoone(cascade = cascadetype.all, mappedby = "consultation") @joincolumn(name = "prescription_id") private prescription prescription; } prescription { @id @generatedvalue(strategy = generationtype.identity) private long id; @onetoone @joincolumn(name = "consultation_id") private consultation consultation; @onetomany(cascade = cascadetype.all, mappedby = "prescription") private set<medicine> medicines; } medicine { @id @generatedvalue(strategy = generationtype.identity) private long id; @manytoone @joincolumn(name = "prescription_id") private prescription prescription; }
the problem:
when call entitymanager.persist(consultation), child entities saved in cascade: prescription , set of medicines, in respective tables. problem foreign keys values null.
- consultation.prescription_id = null
- prescription.consultation_id = null
- medicine.prescription_id = null
hibernate hql logs:
insert prescriptions (consultation_id, prescription_type) values (?, ?) insert medicines (description, name, prescription_id) values (?, ?, ?) insert consultations (cost, date_occured, description, diagnosis, employee_id, patient_id, reference_id) values (?, ?, ?, ?, ?, ?, ?)
what did misunderstand in cascading mechanism?
it seems did not update owner sides of associations; hibernate not check inverse sides when flushing associations database.
make sure update consultation
field in prescription
, , prescription
field in medicine
.
cascading has nothing ownership of associations; determines entity lifecycle operation cascaded associated entities.
Comments
Post a Comment