Home > Software design >  Update and delete Entity contains another Entity One To many Many to one relationship java
Update and delete Entity contains another Entity One To many Many to one relationship java

Time:08-13

I have an application with the use case A Patient or Doctor has one or more appointments. I have the entities like this: Entiy Patient

@Entity
@AllArgsConstructor 
@NoArgsConstructor
@Data
public class Patient {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idPatient;
@Column(length = 80)
private String name;
private String mail;
@Temporal(TemporalType.DATE)
private Date dateNaissance;
private boolean malade;
@OneToMany(mappedBy = "patient", fetch = FetchType.LAZY)
private Collection<RendezVous> rendezVousPatient;
}

And the entity of Doctor

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Medecin {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idMedecin;
@Column(length = 80)
private String name;    
private String email;
private String speciality;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@OneToMany(mappedBy = "medecin", fetch = FetchType.LAZY)
private Collection<RendezVous> rendezVousMedecin;
}

Here the Entity of Appointment

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RendezVous {

@Id
private String idRDV;
@Temporal(TemporalType.DATE)
private Date dateRDV;
@Enumerated(EnumType.STRING)
private StatusRDV status;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@ManyToOne
private Patient patient;
@ManyToOne
private Medecin medecin;
@OneToOne(mappedBy = "rendezVous")

} Each entity has its DTO and here are the entities in DTO: DTO of Patient

@Data
public class PatientDTO {

private Long idPatient;
@NotNull(message = "Name does not null")
private String name;
@Email(message = "Email is not Valid")
private String mail;
private Date dateNaissance;
private boolean malade;
private Collection<RendezVous> rendezVousPatient;
}

DTO of Doctor

@Getter
@Setter
public class MedecinDTO {

private Long idMedecin;
@NotBlank(message = "Name does not Null")
private String name;
@Email(message = "Mail not Valid")
private String email;
@NotNull(message = "the doctor must have a speciality. ")
private String speciality;
private Collection<RendezVous> rendezVousMedecin;
}

And the final DTO of Appointment

@Data
public class RendezVousDTO {

private String idRDV;
private Date dateRDV;
private StatusRDV status;

private Patient patient;

private Medecin medecin;

}

And in the service on impliments here is the code of Update and Delete

@Service
@Transactional
public class IhospitalImpl implements Ihospital {

Logger logger = LoggerFactory.getLogger(IhospitalImpl.class);

@Autowired
private PatientMapperImpl patientMapper;
@Autowired
private MedecinMapperImpl medecinMapper;
@Autowired
private RendezVousMapper rendezVousMapper;

@Override
public MedecinDTO updateMedecin(MedecinDTO medecinDTO, Long id) throws 
MedecinNotFoundException, RendezVousNotFound {
    Medecin medecin = medecinMapper.fromMedecinDTO(medecinDTO);
    Medecin currentMedecin = medecinMapper.fromMedecinDTO(findMedecinById(id));
    if (!medecin.getEmail().isEmpty()) {
        currentMedecin.setEmail(medecin.getEmail());
    }
    if (!medecin.getName().isEmpty()) {
        currentMedecin.setName(medecin.getName());
    }
    if (medecin.getRendezVousMedecin() != null) {
        currentMedecin.setRendezVousMedecin(medecin.getRendezVousMedecin());            
    }
    if (!medecin.getSpeciality().isEmpty()) {
        currentMedecin.setSpeciality(medecin.getSpeciality());
    }
    MedecinDTO savedMedecinDTO = 
                medecinMapper.fromMedecin(medecinRepository.save(currentMedecin));
    return savedMedecinDTO;
}

@Override
public PatientDTO upDatePatient(PatientDTO patientDTO, Long id) throws 
                PatientNotFoundException {
    Patient patient = patientMapper.fromPatientDTO(patientDTO);
    Patient currentPatient = patientMapper.fromPatientDTO(findPatienById(id));
    if (patient.getDateNaissance() != null) {
        currentPatient.setDateNaissance(patient.getDateNaissance());
    }
    if (patient.getMail() != null) {
        currentPatient.setMail(patient.getMail());
    }
    if (patient.getName() != null) {
        currentPatient.setName(patient.getName());
    }
    if (patient.getRendezVousPatient() != null) {
        currentPatient.setRendezVousPatient(patient.getRendezVousPatient());
    }
    PatientDTO savedPatient = 
               patientMapper.fromPatient(patientRepository.save(currentPatient));
    return savedPatient;
}

@Override
public RendezVousDTO updateRendezVous(RendezVousDTO rendezVousDTO, String id) throws 
              RendezVousNotFound {
    RendezVous rendezVous = rendezVousMapper.fromRendeVousDTO(rendezVousDTO);
    RendezVous currentRendezVous = rendezVousMapper.fromRendeVousDTO(findRDVById(id));
    if (rendezVous.getConsultation() != null) {
        currentRendezVous.setConsultation(rendezVous.getConsultation());
    }
    if (rendezVous.getDateRDV() != null) {
        currentRendezVous.setDateRDV(rendezVous.getDateRDV());
    }
    if (rendezVous.getMedecin() != null) {
        currentRendezVous.setMedecin(rendezVous.getMedecin());
    }
    if (rendezVous.getPatient() != null) {
        currentRendezVous.setPatient(rendezVous.getPatient());
    }
    if (rendezVous.getStatus() != null) {
        currentRendezVous.setStatus(rendezVous.getStatus());
    }
    RendezVousDTO savedRDV = 
              rendezVousMapper.fromRendezVous(rendezVousRepository.save(currentRendezVous));
    return savedRDV;
  }
}

@Override
public Map<String, Boolean> deletePatient(Long id) throws PatientNotFoundException {
    Patient patient = patientRepository.findById(id).orElseThrow(() -> new 
            PatientNotFoundException("Patient Not Found with id : "   id));
    patientRepository.delete(patient);
    Map<String, Boolean> mapDelete = new HashMap<>();
    mapDelete.put("Delete Patient", Boolean.TRUE);
    return mapDelete;
}

@Override
public Map<String, Boolean> deleteMedecin(Long id) throws MedecinNotFoundException {
    MedecinDTO medecinDTO = getMedecin(id);
    medecinRepository.delete(medecinMapper.fromMedecinDTO(medecinDTO));
    Map<String, Boolean> mapDelete = new HashMap<>();
    mapDelete.put("Delete Medecin", Boolean.TRUE);
    return mapDelete;
}

@Override
public Map<String, Boolean> deleteRDV(String id) throws RendezVousNotFound {
    RendezVousDTO rendezVousDTO = findRDVById(id);
    rendezVousRepository.delete(rendezVousMapper.fromRendeVousDTO(rendezVousDTO));
    Map<String, Boolean> mapDelete = new HashMap<>();
    mapDelete.put("Delete Rendez vous", Boolean.TRUE);
    return mapDelete;
   }
}

The problem if I am going to modify one of the DTOs: the attributes of the Patient or doctor it works but the other modifications cannot be modified. For example if I want to modify the attribute name, mail it will work but if I want to modify the Appointment I cannot. And the same for the appointment. I tried with POSTMAN and still there is an exception happening with debug

Method threw 'org.hibernate.LazyInitializationException' exception. Cannot evaluate com.example.Entities.Patient.toString()

without debug at the intellij console

java.lang.NullPointerException: null

And for deletion If I want to delete a Patient with or without an appointment. The deletion is done successfully. But the problem the patient is deleted in the DB, however the appointment which is related to the patient or the doctor already exists in the DB and with the command of getRDV the exception message is displayed that the appointment does not exist.

I hope I have explained well and thank you for all who help me.

CodePudding user response:

According to what you said, your data has been saved in the database, but it cannot be returned to your control page correctly, and your program will respond when using postman, but the corresponding lack cannot be mapped to the parameters of the corresponding class, you Are the wrong paths and parameters mapped on your controller? I hope you can show your control class, and when the database can save the information, your logic should be fine, but the returned data map should have an error, you can try to pass the parameter with your field name Agree, hope this helps you.

CodePudding user response:

For My Controller it's the same

@RestController
@RequestMapping("/api/rdv")
public class RendezVousController {

@Autowired
private Ihospital ihospital;

@GetMapping("/rendezVousById/{id}")
public ResponseEntity<RendezVousDTO> getRDV(@PathVariable("id") String id) throws RendezVousNotFound {
    return new ResponseEntity<>(ihospital.findRDVById(id), HttpStatus.OK);
}

@GetMapping("/rendezVous")
public ResponseEntity<List<RendezVousDTO>> getAllRDV() throws RendezVousNotFound {
    return new ResponseEntity(ihospital.findAllRDV(), HttpStatus.OK);
}

@PostMapping("/rendezVousPost")
public ResponseEntity<RendezVousDTO> saveRDV(@RequestBody RendezVousDTO rendezVousDTO) {
    return new ResponseEntity<>(ihospital.saveRDV(rendezVousDTO), HttpStatus.CREATED);
}

@PutMapping("rendezVousPut/{id}")
public ResponseEntity<RendezVousDTO> updateRendezVous(@RequestBody RendezVousDTO rendezVousDTO, @PathVariable("id") String id) throws RendezVousNotFound {
    return ResponseEntity.ok(ihospital.updateRendezVous(rendezVousDTO, id));
}

@DeleteMapping("/rendezVousDelete/{id}")
public ResponseEntity<Map<String, Boolean>> deleteRDV(@PathVariable("id") String id) throws RendezVousNotFound {
    Map<String, Boolean> response = ihospital.deleteRDV(id);
    return ResponseEntity.ok(response);
}

}

The same for the Doctor and the Patient for the Controller

I can only modify the direct attributes like name, email and specility for the MedecinDTO. And name, email and dateBirth for the PatientDTO. And dateRDV and status for RendezVousDTO but I cannot modify the Patient or the Doctor through RendezVousDTO I don't know if the rule implies that or I don't know how to do it with Postman. The problem I can or I can't And thank you I can to delete or Modify any DTOs in the direct Controller but i can't to delete or Modify in another Controller

  • Related