使用后请求插入记录时,未链接与外键相关的参考记录。

@RestController
@RequestMapping("auth")
public class PatientController {

    @Autowired
    private PatientService patientService;

    @PostMapping(value = "patient/register", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public String registerPatient(@RequestBody Patient patient) {
        String response = patientService.registerPatient(patient);
        return "{'result':" + response + "}";
    }
}

@Service
public class PatientService {

    @Autowired
    private PatientRepository patientRepo;

    public String registerPatient(Patient patient) {
        patient = patientRepo.save(patient);
    }
}

@Repository
public interface PatientRepository extends CrudRepository<Patient, Integer> {

}


实体类别:

@Entity
@Table(name = "patient")
public class Patient implements java.io.Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "patient_id")
    private int patientId;

    @Column(name = "patient_name", length = 200)
    private String patientName;

    @Column(name = "problem", length = 200)
    private String problem;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "doctor_id", nullable = false, insertable = false, updatable = false)
    private Doctor doctor;

}

@Entity
@Table(name = "doctor")
public class Doctor implements java.io.Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "doctor_id")
    private int doctorId;

    @Column(name = "doctor_name", length = 200)
    private String doctorName;

    @Column(name = "department", length = 200)
    private String department;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "doctor")
    private Set<Patient> patients = new HashSet<Patient>(0);

}


数据库-Doctor Table:
doctor_id doctor_name科室
12345678 Dfirstname Dlastname ENT

POST请求-JSON正文
{
“ patientName”:“ Pfirstname Plastname”,
“问题:“可见度问题-弱光困难”,
“ doctor”:{“ doctorId”:“ 12345678”}
}

当我发送此请求时,患者表doctor_id列未填充docortId。

最佳答案

乍一看(由于未提供服务层),您必须从@JoinColumn中删除insertable = false和updatable = false

@JoinColumn(name = "doctor_id", nullable = false, insertable = false, updatable = false)

更改为:

@JoinColumn(name = "doctor_id", nullable = false)

由于此指令不允许jpa插入/更新DOCTOR_ID

我也更喜欢在原始类型上使用werappers作为@Id将int更改为Integer,如这里Using wrapper Integer class or int primitive in hibernate mapping

同样,您似乎已经坚持了doctor(因为它已经分配了ID),您应该首先选择db的Doctor,并在两端都添加耐心:

public void assignToDoctor(Doctor doctor) {
        doctor.patients.add(this);
        this.doctor = doctor;
}


这是完整的示例:

    public static void main(String[] args) {
        SpringApplication.run(DemostackApplication.class, args);
    }


    @Component
    public static class AppRunner implements ApplicationRunner {

        @Autowired
        MainService mainService;

        @Override
        public void run(ApplicationArguments args) throws Exception {
            Doctor doctor = new Doctor();
            doctor.department = "a";
            doctor.doctorName = "Covid19 Ninja";
            doctor = mainService.saveDoctor(doctor);

            Patient patient = new Patient();
            patient.patientName = "test";
            patient.problem = "test";
            patient.assignToDoctor(doctor);
            Patient newPatient = mainService.savePatient(patient);
        }
    }

    @Service
    public static class MainService {
        @Autowired
        DoctorRepo doctorRepo;
        @Autowired
        PatientRepo patientRepo;

        @Transactional
        public Doctor saveDoctor(Doctor doctor) {
            return doctorRepo.save(doctor);
        }

        @Transactional
        public Patient savePatient(Patient patient) {
            return patientRepo.save(patient);
        }
    }

    @Entity
    @Table(name = "patient")
    public static class Patient implements java.io.Serializable {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "patient_id")
        private Integer patientId;

        @Column(name = "patient_name", length = 200)
        private String patientName;

        @Column(name = "problem", length = 200)
        private String problem;

        @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name = "doctor_id", nullable = false)
        private Doctor doctor;

        public void assignToDoctor(Doctor doctor) {
            doctor.patients.add(this);
            this.doctor = doctor;
        }
    }

    @Entity
    @Table(name = "doctor")
    public static class Doctor implements java.io.Serializable {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "doctor_id")
        private Integer doctorId;
        @Column(name = "doctor_name", length = 200)
        private String doctorName;

        @Column(name = "department", length = 200)
        private String department;

        @OneToMany(fetch = FetchType.LAZY, mappedBy = "doctor")
        private Set<Patient> patients = new HashSet<Patient>(0);
    }


我没有使用getter / setter,但是您应该:)

编辑

您的registerPatient()逻辑应如下所示:

    @Transactional
    public String registerPatient(Patient patient) {
         Integer doctorId= patinet.getDoctor().getId();
         //fetch the doctor from database
         Doctor doctor = doctorRepository.findById(doctorId).orElseThrow(() -> new RuntimeException("doctor not found"));
         //create bidirectional reference between patient and doctor
         patient.setDoctor(doctor);
         doctor.getPatients().add(patient);
         //save patient
         patient = patientRepo.save(patient);
         return "OK";
    }

10-05 17:45
查看更多