There is a nice and elegant way to do this. It relies on the use of Hibernate proxies in conjunction with extracting a many-to-many relationship to a single object, for example:
@Entity public class HospitalToDoctor implements Serializable { @Id @ManyToOne private Hospital hospital; @Id @ManyToOne private Doctor doctor; } @Entity public class Hospital { @OneToMany(mappedBy = "hospital") private Collection<HospitalToDoctor> doctors; } @Entity public class Doctor { @OneToMany(mappedBy = "doctor") private Collection<HospitalToDoctor> hospitals; }
Now, to map a Doctor and a Hospital just one insert instructor without any additional database calls:
HospitalToDoctor hospitalToDoctor = new HospitalToDoctor(); hospitalToDoctor.setHospital(entityManager.getReference(Hospital.class, hospitalId)); hospitalToDoctor.setDoctor(entityManager.getReference(Doctor.class, doctorId)); entityManager.persist(hospitalToDoctor);
The key point here is to use EntityManager.getReference :
Get an instance whose state can be lazily retrieved.
Hibernate will simply create a proxy server based on the provided id without getting the entity from the database.
In other use cases, you can encapsulate the HospitalToDoctor object so that the association is still used as many-to-many. For example, you can add something like this to Hopsital :
public Collection<Doctor> getDoctors() { Collection<Doctor> result = new ArrayList<>(doctors.size()); for (HospitalToDoctor hospitalToDoctor : doctors) { result.add(hospitalToDoctor.getDoctor()); } return result; }
An additional advantage of introducing HospitalToDoctor is that you can easily store additional attributes in it if such a need arises (for example, when the doctor started working in the hospital, etc.).
However, if you still do not want to enter a separate object, but want to use pure Hibernate many-to-many, you can still use proxies. You can add the Doctor proxy to a busy Hospital (or vice versa). You can also look at Hibernate for additional lazy collections to avoid loading the doctors collection when adding Doctor to Hospital or vice versa (the main problem of your question, I suppose).
Dragan bozanovic
source share