A unidirectional association via a join table
@Entity
class Patient {
@OneToMany
private Collection<Vehicle> vehicles = new ArrayList<Vehicle>();
}
@Entity
class Vehicle {
}
A bidirectional association via a join table
@Entity
class Patient {
@OneToMany
private Collection<Vehicle> vehicles = new ArrayList<Vehicle>();
}
@Entity
class Vehicle {
@ManyToOne(fetch = FetchType.LAZY)
private Patient patient;
}
A unidirectional association via a foreign key
@Entity
class Patient {
@OneToMany
@JoinColumn
private Collection<Vehicle> vehicles = new ArrayList<Vehicle>();
}
@Entity
class Vehicle {
}
A bidirectional association via a foreign key
@Entity
class Patient {
@OneToMany(mappedBy = "patient")
private Collection<Vehicle> vehicles = new ArrayList<Vehicle>();
}
@Entity
class Vehicle {
@ManyToOne(fetch = FetchType.LAZY)
private Patient patient;
}
A bidirectional association via a foreign key with a foreign column name specification
@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;
}
This is the basic starting point of using @JoinColumn
.
To verify that the foreign key(patient_id
in the Vehicle
table) is really mapped in the patients table you can use @JoinColumn(nullable = false)
@Entity
class Vehicle {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="patient_id", nullable = false)
private Patient patient
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…