我有兩個物體類Medicine和Medicine Group。一種藥物屬于一個群體。一個群體擁有不止一種藥物。醫學與群體的關系是一對一的,群體與醫學的關系是一對多的。
我創建了具有以下屬性的物體類
@Entity
public class Medicine {
@Id
String medicineId;
String medicineName;
int inStock;
String lifetimeSupply;
String lifetimeSales;
String howToUse;
String sideEffects;
//their getters and setters
}
@Entity
public class MedicineGroup {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
int groupId;
String groupName;
String groupDescription;
//their getters and setters.
}
在Medicine 表的MySQL中,我有一個名為groupId的列,它是組表的外鍵。
通常在 MySQL 中我可以寫一個這樣的連接陳述句
SELECT drug_id ,medicine_name ,in_stock ,lifetime_supply,lifetime_sales, how_to_use, side_effects , group_name FROM drug JOIN drug_group on drug.group_id = drug_group.group_id;
在上面的連接中,我可以從組表中獲取組名列。如何使用 JPA 實作這一點。如果我像這樣向醫學類添加一個欄位
@OneToOne
MedicineGroup medicineGroup;
當我執行獲取請求時,我收到錯誤Unknown column 'medicine0_.medicine_group_group_id' in 'field list'。欄位未知,但我在醫學表中有一個名為 group_id 的列?
如果我執行獲取請求,我怎樣才能獲得藥物資訊以及與之關聯的組? 請幫忙。
uj5u.com熱心網友回復:
屬性的簡單連接:
SELECT m.medicineId ,m.medicineName ,m.inStock ,m.lifetimeSupply, m.lifetimeSales, m.howToUse, m.sideSffects , mg.groupName
FROM medicine m join m.medicineGroup mg;
并使用屬性名,而不是列名
uj5u.com熱心網友回復:
select m from medicine m left join fetch m.medecineGroup
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/475595.html
