Spring Boot 当我把特定药物的列表放在控制器上时,我有问题,但当我把药物名称放在mySQL中时,我没有问题

ajsxfq5m  于 2023-01-30  发布在  Spring
关注(0)|答案(1)|浏览(100)

2023 - 01 - 28 13:55:33.706警告17396---[nio-8080-exec-7]. w.s.m.s.默认处理程序异常解析程序:已解决[org. springframework. validation.绑定异常:org.Spring框架.验证. Bean属性绑定结果:1个错误字段"药物"上对象"患者"中的字段错误:拒收值[必理多];代码[类型不匹配.患者.药物,类型不匹配.药物,类型不匹配. java. util.集合,类型不匹配];参数[org. springframework. context. support.默认消息源可解析:代码[患者、药物、药物];参数[];默认消息[药物]];默认消息[无法将属性"drugs"的类型"java.lang.String"的属性值转换为所需类型"java.util.Set";嵌套异常是org. springframework. core.转换。转换失败异常:无法将值"panadol"从类型[java. lang. String]转换为类型[java. lang. Long];嵌套异常是java. lang. NumberFormatException:对于输入字符串:"必理通"]] "panadol"]]

package com.example.prescription.model;

import javax.persistence.*;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Date;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;

@Entity
@Table(name = "patients")
public class Patient implements Serializable {
private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "dob")
    private String dateOfBirth;

    @NotEmpty(message = "Phone number may not be empty")
    @Size(min = 10, max = 10)
    @Column(name = "phone")
    private String phone;

    @NotEmpty(message = "Email may not be empty")
    @Size(min = 7, max = 50)
    @Column(name = "email")
    private String email;

    @Column(name = "fathers_name")
    private String fathersName;

    @Column(name = "mothers_name")
    private String mothersName;

    @Column(name = "amka")
    @Size(min = 11, max = 11)
    @Pattern(regexp = "^[0-9]+$", message = "AMKA must contain only numbers")
    private String amka;

    @Column(name = "id_card")
    @Pattern(regexp = "^[a-zA-Z0-9]+$", message = "ID must contain only letters and numbers")
    private String idCard;

    @Column(name = "city")
    private String city;

    @Column(name = "postal_code")
    @Size(min = 5, max = 5)
    @Pattern(regexp = "^[0-9]+$", message = "PC must contain only numbers")
    private String postalCode;

    @Column(name = "symptoms")
    private String symptoms;

    @Column(name = "pharmacy")
    private String pharmacy;

    @Column(name = "doctor_name")
    private String doctorsName;

    @Column(name = "message")
    private String message;

    @ManyToMany(cascade = {CascadeType.PERSIST,CascadeType.MERGE})
    @JoinTable(name = "patient_drug",joinColumns = @JoinColumn(name = "patient_id"),
    inverseJoinColumns = @JoinColumn(name = "drug_id"))
    private Set<Drug> drugs;

    public Patient(Patient patient, Drug drug, Date date) {
    }

    public Patient() {

    }

    public void addDrug(Drug drug){
       this.drugs.add(drug);
       drug.getPatients().add(this);
   }
   public void removeDrug(Drug drug) {
       this.drugs.remove(drug);
       drug.getPatients().remove(this);
   }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(String dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFathersName() {
        return fathersName;
    }

    public void setFathersName(String fathersName) {
        this.fathersName = fathersName;
    }

    public String getMothersName() {
        return mothersName;
    }

    public void setMothersName(String mothersName) {
        this.mothersName = mothersName;
    }

    public String getAmka() {
        return amka;
    }

    public void setAmka(String amka) {
        this.amka = amka;
    }

    public String getIdCard() {
        return idCard;
    }

    public void setIdCard(String idCard) {
        this.idCard = idCard;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getPostalCode() {
        return postalCode;
    }

    public void setPostalCode(String postalCode) {
        this.postalCode = postalCode;
    }

    public String getSymptoms() {
        return symptoms;
    }

    public void setSymptoms(String symptoms) {
        this.symptoms = symptoms;
    }

    public String getPharmacy() {
        return pharmacy;
    }

    public void setPharmacy(String pharmacy) {
        this.pharmacy = pharmacy;
    }

    public String getDoctorsName() {
        return doctorsName;
    }

    public void setDoctorsName(String doctorsName) {
        this.doctorsName = doctorsName;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Set<Drug> getDrugs() {
        return drugs;
    }

    public void setDrugs(Set<Drug> drugs) {
        this.drugs = drugs;
    }

    public void removeDrugs() {
        Iterator<Drug> iterator = this.drugs.iterator();
        while (iterator.hasNext()) {
            Drug drug = iterator.next();
            drug.getPatients().remove(this);
            iterator.remove();
        }

    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Patient patient = (Patient) o;
        return Objects.equals(id, patient.id) && Objects.equals(firstName, patient.firstName) && Objects.equals(lastName, patient.lastName) && Objects.equals(dateOfBirth, patient.dateOfBirth) && Objects.equals(phone, patient.phone) && Objects.equals(email, patient.email) && Objects.equals(fathersName, patient.fathersName) && Objects.equals(mothersName, patient.mothersName) && Objects.equals(amka, patient.amka) && Objects.equals(idCard, patient.idCard) && Objects.equals(city, patient.city) && Objects.equals(postalCode, patient.postalCode) && Objects.equals(symptoms, patient.symptoms) && Objects.equals(pharmacy, patient.pharmacy) && Objects.equals(doctorsName, patient.doctorsName) && Objects.equals(message, patient.message) && Objects.equals(drugs, patient.drugs);
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Patient{");
        sb.append("id=").append(id);
        sb.append(", firstName='").append(firstName).append('\'');
        sb.append(", lastName='").append(lastName).append('\'');
        sb.append(", dateOfBirth='").append(dateOfBirth).append('\'');
        sb.append(", phone='").append(phone).append('\'');
        sb.append(", email='").append(email).append('\'');
        sb.append(", fathersName='").append(fathersName).append('\'');
        sb.append(", mothersName='").append(mothersName).append('\'');
        sb.append(", amka='").append(amka).append('\'');
        sb.append(", idCard='").append(idCard).append('\'');
        sb.append(", city='").append(city).append('\'');
        sb.append(", postalCode='").append(postalCode).append('\'');
        sb.append(", symptoms='").append(symptoms).append('\'');
        sb.append(", pharmacy='").append(pharmacy).append('\'');
        sb.append(", doctorsName='").append(doctorsName).append('\'');
        sb.append(", message='").append(message).append('\'');
        sb.append('}');
        return sb.toString();
    }
}
package com.example.prescription.controller;

import com.example.prescription.model.Drug;
import com.example.prescription.model.Patient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import com.example.prescription.service.DrugService;
import com.example.prescription.service.PatientService;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class PatientController {

    private final PatientService patientService;
    private final DrugService drugService;

    public PatientController(@Autowired PatientService patientService,
                             @Autowired DrugService drugService) {
        this.patientService = patientService;
        this.drugService = drugService;

    }

    //read
    @GetMapping("/allPatients")
    public String getAllPatients(Model model) {
        List<Patient> patientList = patientService.getAllPatients();
        model.addAttribute("patientList", patientList);
        return "patients";
    }

//edit

    @GetMapping("/newPatient")
    public ModelAndView register() {
        ModelAndView mav = new ModelAndView("patientForm");
        mav.addObject("patient", new Patient());
        mav.addObject("drugs", drugService.getAllDrugs());
        return mav;
    }

    //save
    @PostMapping("/patient/save")
    public String savePatient(Patient patient) {
        patientService.savePatient(patient);
        return "redirect:/allPatients";

    }
//update

    @GetMapping("/editPatient/{id}")
    public ModelAndView editPatient(@PathVariable(value = "id") String id) {
        ModelAndView mav = new ModelAndView("patientFormEditToUpdate");
        Long pid = Long.parseLong(id);
        Patient formPatient = patientService.findPatientById(pid);
        mav.addObject("patient", formPatient);
        return mav;
    }

    @PostMapping("/updatePatient/patient/{id}")
    public String updatePatient(@PathVariable(value = "id") String id, Patient patient) {
        Long pid = Long.parseLong(id);
        Patient patient1 = patientService.findPatientById(pid);
        patient1 = patient;
        patientService.updatePatient(patient1);
        return "redirect:/allPatients";

    }

    //delete
    @GetMapping("/delete/{id}")
    public String deleteById(@PathVariable(value = "id") String id) {
        Long pid = Long.parseLong(id);
        Patient deletedPatient = patientService.findPatientById(pid);
        patientService.deletePatient(deletedPatient);
        return "redirect:/allPatients";
    }

    @GetMapping("/prescribeDrugs/{id}")
    public ModelAndView prescribeDrugs(@PathVariable("id") String id) {


        Long pid = Long.parseLong(id);
        ModelAndView mav = new ModelAndView("patientFormEdit");
        Patient formPatient = patientService.findPatientById(pid);
        mav.addObject("patient", formPatient);
        mav.addObject("drugs", drugService.getAllDrugs());
        mav.addObject("drugList",drugList);
        return mav;

    }

    static List<String> drugList= null;



    static{
        drugList = new ArrayList<>();
        drugList.add("depon");
        drugList.add("aspirin");
        drugList.add("panadol");

    }

@PostMapping("/prescribeDrugs/Patient/{id}")
  public String prescribePatientDrugs(@Valid Patient patient,String id,    @ModelAttribute(value = "drugs")Long drugId ,BindingResult result)
 {

     if(result.hasErrors())
     {

         return "patients";
     }

    try {
        Long pId = Long.parseLong(id);
        Patient formPatient = patientService.findPatientById(pId);

       Drug drug = drugService.findById(drugId);
       formPatient.setCity(patient.getCity());
       formPatient.setEmail(patient.getEmail());
       formPatient.setPhone(patient.getPhone());
       formPatient.setSymptoms(patient.getSymptoms());
       formPatient.setPharmacy(patient.getPharmacy());
       formPatient.setDoctorsName(patient.getDoctorsName());
       formPatient.setMessage(patient.getMessage());
       Drug patientDrug= new Drug(patient, drug, new Date());
       drugService.save(drug);
       formPatient.getDrugs().add(patientDrug);
       patientService.updatePatient(formPatient);
    }catch (NumberFormatException numberFormatException){
        System.out.println("error");
    }

        return "redirect:/allPatients";
}

}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>
  <link th:href="@{/css/webform.css}" href="/css/webform.css" rel="stylesheet" type="text/css"/>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <title>Update Patient</title>
</head>

<script type="text/javascript" th:src="@{/js/webform.js}"></script>

<form th:action="@{/prescribeDrugs/Patient/{id}(id = ${patient.id})}" method="post" th:object="${patient}">
  <div class="container prescription-form">
    <div class="row">
      <div class="col-lg-12 col-12">
        <form>
          <h1>Electronic Prescription Form</h1>
          <div class="row">
            <div class="col-lg-6 col-12">
              <label>
                <span>Patient Name</span><input type="text" th:value="${patient.firstName}"
                                                th:name="firstName" disabled/>
              </label>
            </div>

            <div class="col-lg-6 col-12">
              <label>
                <span>Patient Email</span><input id="email" type="text" th:value="${patient.email}"
                                                 th:name="email"/>
              </label>
            </div>
          </div>

          <div class="row">
            <div class="col-lg-6 col-12">
              <label>
                <span>Patient Surname</span><input id="surname" type="text"
                                                   th:value="${patient.lastName}" th:name="surname"
                                                   disabled/>
              </label>
            </div>

            <div class="col-lg-6 col-12">
              <label>
                <span>Patient Phone</span><input id="phone" type="text" th:value="${patient.phone}"
                                                 th:name="phone"/>
              </label>
            </div>
          </div>

          <div class="row">
            <div class="col-lg-6 col-12">
              <label>
                <span>Patient Symptoms</span><input id="symptoms" type="text" th:name="symptoms"
                                                    required/>
              </label>
              <span class="error_message">This field is required</span>
            </div>

        
              <span class="error_message">This field is required</span>
            </div>
     
       
          <div class="col-lg-6 col-12" >
            <label>
              <span>Drug*</span>
             <select name="drugs">
                <option th:each="drug : ${drugList}"
                        th:text="${drug}">
              </select>
            </label>
            <span class="error_message">This field is required</span>
          </div>

          <div class="row">
            <div class="col-lg-6 col-12">
              <label>
                <span>AMKA</span><input id="amka" type="text" th:value="${patient.amka}" th:name="amka"
                                        disabled/>
              </label>
            </div>

            <div class="col-lg-6 col-12">
              <label>
                <span>Patient ID</span><input id="patient_id" type="text" th:value="${patient.idCard}"
                                              th:name="patient_id" disabled/>
              </label>
              <span class="error_message">This field is required</span>
            </div>
          </div>

          <div class="row">
            <div class="col-lg-6 col-12">
              <div class="message pharmacy">
                <label class="miniTextfield">
                  <span>Pharmacy to deliver</span><textarea id="pharmacy" th:name="pharmacy" required></textarea>
                </label>
                <span class="error_message">This field is required</span>
              </div>

            </div>

            <div class="col-lg-6 col-12">
              <div class="message signature">
                <label class="miniTextfield">
                  <span>Doctor Signature</span><textarea id="doctorSignature" th:name="doctorsName" required></textarea>
                </label>
                <span class="error_message">This field is required</span>
              </div>

            </div>
          </div>

          <div class="row">

            <div class="col-lg-6 col-12">
              <label>
                <span>City</span><input id="city" type="text" th:value="${patient.city}" th:name="city"
              />
              </label>
            </div>
          </div>

          <div class="message">
            <div class="col-lg-12 col-12">
              <label class="message_btn_wrapper">
                <span>Message</span><textarea id="feedback" th:name="message"></textarea>
                <input type="submit" value="Submit Form"/>
                <div class="requiredMessage">Fields with * are mandatory</div>
              </label>
            </div>

          </div>
        </form>
      </div>
    </div>
  </div>
</form>
khbbv19g

khbbv19g1#

在控制器中,您正在添加String类型的Drug对象列表,但它们不是Drug类型。您的Patient需要Drug对象的Set
在这段代码中还存在其他一些问题,但是要直接使用构造函数或使用Builder模式创建Drug对象的新Set
例如:如:
Set.of(new Drug("depon"), new Drug("aspirin"), new Drug("panadol"));
但是针对您的Drug构造函数进行了调整。
看看我的公开资料库中的一些工作代码。
https://github.com/vphilipnyc/For_Vasileios_Maziotis

相关问题