我已经阅读了很多有关@JoinColumn的内容,但是我仍然不明白它的含义。
患者表
CREATE TABLE patient (
patient_id BIGINT NOT NULL,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
PRIMARY KEY(patient_id));
车辆表
CREATE TABLE vehicles (
patient_id BIGINT NOT NULL,
vehicle_id BIGINT NOT NULL,
vehicle_manufacturer VARCHAR(255),
PRIMARY KEY (vehicle_id),
CONSTRAINT patienthasmanyvehicle FOREIGN KEY(patient_id) REFERENCES patient(patient_id));
患者分类
@OneToMany(mappedBy = "patient")
private Collection<Vehicle> patientVehicles = new ArrayList<Vehicle>();
车辆类别
@ManyToOne
@JoinColumn(name="patient_id")
private Patient patient;
我对Vehicle类的部分感到困惑,两者之间的关系是什么
Vehicle Class ---- Entity
@JoinColumn(name="patient_id") ---- annotation
private Patient patient ----field
会说吗? 车辆实体具有到患者实体的外键,名为 Patient_id Patient_id 。
将 Patient_id 添加为 Vehicle Entity表中的一列
JoinColumn的名称参数应该始终是外键还是主键?
我读过这篇文章,但仍然感到困惑。
JPA JoinColumn vs mappedBy
最佳答案
通过联接表的单向关联
@Entity
class Patient {
@OneToMany
private Collection<Vehicle> vehicles = new ArrayList<Vehicle>();
}
@Entity
class Vehicle {
}
通过联接表的双向关联
@Entity
class Patient {
@OneToMany
private Collection<Vehicle> vehicles = new ArrayList<Vehicle>();
}
@Entity
class Vehicle {
@ManyToOne(fetch = FetchType.LAZY)
private Patient patient;
}
通过外键的单向关联
@Entity
class Patient {
@OneToMany
@JoinColumn
private Collection<Vehicle> vehicles = new ArrayList<Vehicle>();
}
@Entity
class Vehicle {
}
通过外键进行双向关联
@Entity
class Patient {
@OneToMany(mappedBy = "patient")
private Collection<Vehicle> vehicles = new ArrayList<Vehicle>();
}
@Entity
class Vehicle {
@ManyToOne(fetch = FetchType.LAZY)
private Patient patient;
}
通过外键与外来列名称规范的双向关联
@Entity
class Patient {
@OneToMany(mappedBy = "patient")
private Collection<Vehicle> vehicles = new ArrayList<Vehicle>();
}
@Entity
class Vehicle {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="patient_id")
private Patient patient;
}
这是使用
@JoinColumn
的基本起点。要验证外键(
patient_id
表中的Vehicle
)是否确实映射到患者表中,可以使用@JoinColumn(nullable = false)
@Entity
class Vehicle {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="patient_id", nullable = false)
private Patient patient
}
关于java - 什么是@JoinColumn以及如何在Hibernate中使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37542208/