什么是@JoinColumn以及如何在Hibernate中使用
我已经阅读了很多有关@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作为列添加到“车辆实体”表中
回答:
通过联接表的单向关联
@Entityclass Patient {
@OneToMany
private Collection<Vehicle> vehicles = new ArrayList<Vehicle>();
}
@Entity
class Vehicle {
}
通过联接表的双向关联
@Entityclass Patient {
@OneToMany
private Collection<Vehicle> vehicles = new ArrayList<Vehicle>();
}
@Entity
class Vehicle {
@ManyToOne(fetch = FetchType.LAZY)
private Patient patient;
}
通过外键进行单向关联
@Entityclass Patient {
@OneToMany
@JoinColumn
private Collection<Vehicle> vehicles = new ArrayList<Vehicle>();
}
@Entity
class Vehicle {
}
通过外键进行双向关联
@Entityclass Patient {
@OneToMany(mappedBy = "patient")
private Collection<Vehicle> vehicles = new ArrayList<Vehicle>();
}
@Entity
class Vehicle {
@ManyToOne(fetch = FetchType.LAZY)
private Patient patient;
}
通过外键与外列名称说明的双向关联
@Entityclass 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)
@Entityclass Vehicle {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="patient_id", nullable = false)
private Patient patient
}
以上是 什么是@JoinColumn以及如何在Hibernate中使用 的全部内容, 来源链接: utcz.com/qa/432711.html