spring-data-jpa 更新和删除实体包含另一个实体一对多多对一关系java

lymnna71  于 2022-11-10  发布在  Spring
关注(0)|答案(3)|浏览(143)

我有一个应用程序,用例为A Patient or Doctor has one or more appointment(病人或医生有一个或多个预约)。我有如下实体:实体患者

@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;
}

而“医生”这个实体

@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;
}

此处的任命实体

@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")

}每个实体都有其DTO,以下是DTO中的实体:患者的DTO

@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

@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;
}

以及任命的最终DTO

@Data
public class RendezVousDTO {

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

private Patient patient;

private Medecin medecin;

}
在impliments上的服务中,这里是更新删除的代码

@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;
   }
}

如果我要修改其中一个DTO,则会出现以下问题:患者或医生的属性可以修改,但其他修改无法修改。例如,如果我想修改属性名称,邮件可以修改,但如果我想修改约会,我就不能修改。约会也是如此。我尝试使用POSTMAN,但调试时仍出现异常
方法引发了“org. hib. LazyInitializationException”异常错误。无法计算com.示例.实体.患者.toString()
在intellij控制台不调试
java.lang.NullPointerException:零值
对于删除,如果我想删除一个有或没有预约的患者。删除成功完成。但问题是,患者在数据库中被删除,但与患者或医生相关的预约已存在于数据库中,使用getRDV命令时,显示异常消息,说明预约不存在。
我希望我已经解释清楚了,谢谢所有帮助我的人。

pftdvrlh

pftdvrlh1#

如果您在Patient实体中添加CascadeType,它将沿着更新RendezVous实体。

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

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

在Map器端还需要做一个更改。如果显式设置rendezVousPatient的Patient并将该rendezVousPatient提供给该患者,它将更新其他值,就像下面的代码一样:

@Component
public class PatientMapper {
    public Patient fromPatientDTO(PatientDTO patientDTO) {
        Patient patient=new Patient();
        BeanUtils.copyProperties(patientDTO,patient);
        for(RendezVous rendezVous:patientDTO.getRendezVousPatient())
            rendezVous.setPatient(patient);
        patient.setRendezVousPatient(patientDTO.getRendezVousPatient());
        return patient;
    }
    public PatientDTO fromPatient(Patient patient) {
        PatientDTO patientDTO=new PatientDTO();
        BeanUtils.copyProperties(patient,patientDTO);
        return patientDTO;
    }
}
hgncfbus

hgncfbus2#

按照你说的,你的数据已经保存在数据库里了,但是不能正确的返回到你的控件页面,你的程序在使用postman的时候会有响应,但是相应的缺少却不能Map到相应类的参数,你是不是把错误的路径和参数Map到你的控制器上了,希望你能显示出你的控件类,当数据库能够保存信息的时候,你的逻辑应该是正确的,但是返回的数据Map应该有一个错误,你可以尝试用你的字段名Agree传递参数,希望这对你有帮助。

wlzqhblo

wlzqhblo3#

对于“我的控制器”,也是如此

@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);
}

}
对于控制器,医生和患者也是如此
我只能修改MedecinDTO的直接属性,如name、email和specility。而name、患者DTO的电子邮件和日期出生。RendezVousDTO的日期RDV和状态,但我无法通过RendezVousDTO修改患者或医生。我不知道规则是否暗示了这一点,或者我不知道如何使用Postman进行修改。问题是我可以或我不能“t谢谢您,我可以删除或修改直接Controller中的任何DTO,但不能删除或修改另一个Controller中的DTO

相关问题