jeudi 13 août 2015

Efficent updating entity in Hibernate

I guess it may be like a newbie question, but still I'd like to know some answers.

Let's say there are entities: Hospital and Doctor (Many-To-Many). Suppose in my controller class I have to fetch all existing doctors and hospitals, and then hire one doctor in a specific hospital

@Controller
public class HospitalController {
  ...
    @RequestMapping("/hireDoctor")
    public String (HttpServletRequest request, Model model) {
        List<Hospital> hospitals = hospitalService.findAllHospitals();
        List<Doctor> doctors = doctorService.findAllDoctors();

        //some logic, in the end we choose just one doctor and one hospital

        Doctor doctor = doctors.get(0);
        Hospital hospital = hospitals.get(0);

        hospitalService.hireDoctor(hospital, doctor);
    }
  ...

@Service
public class HospitalService {
  ..  
    @Transactional
    public void hireDoctor(Hospital hospital, Doctor doctor) {
        //ideally
        List<Doctor> doctors = hospital.getDoctors();
        doctors.add(doctor);

        this.em.merge(hospital);
    }
  ..
}

It of course doesn't work, because - as I understand - I've fetched all doctors and hospitals in my controller and then in hireDoctor method we're opening trasaction passing regular Java objects, which are not in a session.

I know, that I can just again fetch Hospital with a speicfic ID, and Doctor with a specific ID and then save it

public void hireDoctor(Hospital hospital, Doctor doctor) {
     Hospital h = hospitalRepo.getHospitalById(hospital.getId());
     Doctor d = hospitalRepo.getDoctorById(doctor.getId());
     List<Doctor> doctors = h.getDoctors();
     doctors.add(d);
}

But it just looks rubbish.

So - how should such update look like to be most efficient?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire