Associazione unidirezionale tramite tabella di join
@Entity class Patient { @OneToMany private Collection<Vehicle> vehicles = new ArrayList<Vehicle>(); }
@Entity class Vehicle { }
Associazione bidirezionale tramite tabella di join
@Entity class Patient { @OneToMany private Collection<Vehicle> vehicles = new ArrayList<Vehicle>(); }
@Entity class Vehicle { @ManyToOne(fetch = FetchType.LAZY) private Patient patient; }
Associazione unidirezionale tramite chiave esterna
@Entity class Patient { @OneToMany @JoinColumn private Collection<Vehicle> vehicles = new ArrayList<Vehicle>(); }
@Entity class Vehicle { }
Associazione bidirezionale tramite chiave esterna
@Entity class Patient { @OneToMany(mappedBy = "patient") private Collection<Vehicle> vehicles = new ArrayList<Vehicle>(); }
@Entity class Vehicle { @ManyToOne(fetch = FetchType.LAZY) private Patient patient; }
Bidirezionale con nome esplicito della colonna esterna
@Entity class Vehicle { @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name="patient_id") private Patient patient; }
Imporre la presenza della chiave esterna
@Entity class Vehicle { @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name="patient_id", nullable = false) private Patient patient }
Questo è il punto di partenza fondamentale per usare @JoinColumn. Ricorda che @JoinColumn va sul lato che possiede la relazione, mentre mappedBy indica il lato inverso.