0
假設我們有以下的醫療狀況:休眠層疊多層
3個實體: 諮詢,有一個可爲空處方。 處方藥一套藥 s。
我模仿他們如下:(剝離不必要的信息Java代碼)
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;
}
問題:
當我打電話entityManager.persist(諮詢),所有的子實體被保存級聯:處方和藥品集合,在各自的表格中。問題是所有的外鍵值都是空的。
- consultation.prescription_id = NULL
- prescription.consultation_id = NULL
- medicine.prescription_id = NULL
Hibernate的HQL日誌:
insert into PRESCRIPTIONS (consultation_id, prescription_type) values (?, ?)
insert into MEDICINES (description, name, prescription_id) values (?, ?, ?)
insert into CONSULTATIONS (cost, date_occured, description, diagnosis, employee_id, patient_id, reference_id) values (?, ?, ?, ?, ?, ?, ?)
我是怎麼在誤解級聯機制?
爲什麼你在'@ OneToOne'的**兩邊有'@ JoinColumn'?你正在冒着可能變得不受歡迎的風險。在「諮詢」中,最好只有沒有連接列的'mappedBy'。 – DuncanKinnear