如何使用 JPA 连接两个表?
How can I join two tables using JPA?
我有两个实体 classes Medicine 和 Medicine Group。一个药属于一个组。一组药物不止一种。药物与组的关系是一对一 组与药物的关系是一对多。
我创建了具有以下属性的实体 classes
@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.
}
在医学 MySQL 中 table 我有一个名为 groupId 的列,它是一个外键到群组 table.
通常在 MySQL 我可以写这样的连接语句
SELECT medicine_id ,medicine_name ,in_stock ,lifetime_supply, lifetime_sales, how_to_use, side_effects , group_name FROM medicine JOIN medicine_group on medicine.group_id = medicine_group.group_id;
在上面的连接中,我能够从组 table 中获取组名列。 如何使用 JPA 实现此目的。
如果我像这样给药物class添加一个字段
@OneToOne
MedicineGroup medicineGroup;
当我执行获取请求时,我在 'field list' 中收到错误 Unknown column 'medicine0_.medicine_group_group_id' 。 这个字段怎么不知道但是我在医学table里面有个叫group_id的栏目?
如何实现一种方法,如果我执行获取请求,我将获得药物信息以及与之关联的组? 请帮忙
简单连接属性:
SELECT m.medicineId ,m.medicineName ,m.inStock ,m.lifetimeSupply, m.lifetimeSales, m.howToUse, m.sideSffects , mg.groupName
FROM medicine m join m.medicineGroup mg;
并使用属性名称,而不是列名称
select m from medicine m left join fetch m.medecineGroup
我有两个实体 classes Medicine 和 Medicine Group。一个药属于一个组。一组药物不止一种。药物与组的关系是一对一 组与药物的关系是一对多。
我创建了具有以下属性的实体 classes
@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.
}
在医学 MySQL 中 table 我有一个名为 groupId 的列,它是一个外键到群组 table.
通常在 MySQL 我可以写这样的连接语句
SELECT medicine_id ,medicine_name ,in_stock ,lifetime_supply, lifetime_sales, how_to_use, side_effects , group_name FROM medicine JOIN medicine_group on medicine.group_id = medicine_group.group_id;
在上面的连接中,我能够从组 table 中获取组名列。 如何使用 JPA 实现此目的。 如果我像这样给药物class添加一个字段
@OneToOne
MedicineGroup medicineGroup;
当我执行获取请求时,我在 'field list' 中收到错误 Unknown column 'medicine0_.medicine_group_group_id' 。 这个字段怎么不知道但是我在医学table里面有个叫group_id的栏目?
如何实现一种方法,如果我执行获取请求,我将获得药物信息以及与之关联的组? 请帮忙
简单连接属性:
SELECT m.medicineId ,m.medicineName ,m.inStock ,m.lifetimeSupply, m.lifetimeSales, m.howToUse, m.sideSffects , mg.groupName
FROM medicine m join m.medicineGroup mg;
并使用属性名称,而不是列名称
select m from medicine m left join fetch m.medecineGroup