2015-07-05 68 views
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(諮詢),所有的子實體被保存級聯:處方和藥品集合,在各自的表格中。問題是所有的外鍵值都是空的。

  1. consultation.prescription_id = NULL
  2. prescription.consultation_id = NULL
  3. 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 (?, ?, ?, ?, ?, ?, ?) 

我是怎麼在誤解級聯機制?

+1

爲什麼你在'@ OneToOne'的**兩邊有'@ JoinColumn'?你正在冒着可能變得不受歡迎的風險。在「諮詢」中,最好只有沒有連接列的'mappedBy'。 – DuncanKinnear

回答

2

看來你並沒有更新關聯的所有者一方;在將關聯刷新到數據庫時,Hibernate不檢查反面。

請務必正確更新consultation字段中的Prescriptionprescription字段Medicine

級聯與組織的所有權無關;它只是確定哪個實體生命週期操作級聯到關聯的實體。