Как создать Restful API для обработки отношения «многие ко многим» в Spring Boot? - PullRequest
2 голосов
/ 25 февраля 2020

В моем весеннем загрузочном проекте у меня есть две таблицы имен: доктора и пациенты . В этих таблицах у меня есть следующие атрибуты:

enter image description here

enter image description here

Теперь дело в том, Я хочу создать соотношение многие ко многим между этими двумя таблицами для назначения , поскольку у одного врача может быть много пациентов, а у одного пациента - у нескольких врачей. Итак, для решения этой проблемы я создал еще одну таблицу с именем встречи, которая будет иметь doctorId и PatientId в качестве внешнего ключа .

Мне нужно создать встречу, используя JSON тело запроса, как показано ниже -

enter image description here

Итак, для этой цели я создал класс модель , как показано ниже -

Назначение. java

@Entity
@Table(name = "appointments")
public class Appointment {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    private Long appointedDoctorId;

    @NotNull
    private Long appointedPatientId;

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


    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "patientId", nullable = false)
    private Patient patient;

    public Long getId() {
        return id;
    }

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


    public Long getAppointedDoctorId() {
        return appointedDoctorId;
    }

    public void setAppointedDoctorId(Long appointedDoctorId) {
        this.appointedDoctorId = appointedDoctorId;
    }

    public Long getAppointedPatientId() {
        return appointedPatientId;
    }

    public void setAppointedPatientId(Long appointedPatientId) {
        this.appointedPatientId = appointedPatientId;
    }

    public Doctor getDoctor() {
        return doctor;
    }

    public void setDoctor(Doctor doctor) {
        this.doctor = doctor;
    }

    public Patient getPatient() {
        return patient;
    }

    public void setPatient(Patient patient) {
        this.patient = patient;
    }
}

Вот Репозиторий class-

AppointmentRepository. java

@Repository
public interface AppointmentRepository extends JpaRepository<Appointment, Long> {

    Page<Appointment> findByDoctorId(Long id, Pageable pageable);

}

Вот мой Сервис interface-

AppointmentService. java

public interface AppointmentService {

    public Page<Appointment> getAllAppointmentByDoctorId(@PathVariable(value = "doctorId") Long id, Pageable pageable);

    public Appointment createAppointment(@Valid @RequestBody Appointment createAppointmentRequest);

}

Вот реализация моего класса Service-

AppointmentServiceImpl. java

@Service
public class AppointmentServiceImpl implements AppointmentService {

    @Autowired
    AppointmentRepository appointmentRepository;


    @Override
    public Page<Appointment> getAllAppointmentByDoctorId(Long id, Pageable pageable) {
        return appointmentRepository.findByDoctorId(id, pageable);
    }

    @Override
    public Appointment createAppointment(@Valid Appointment createAppointmentRequest) {
        return appointmentRepository.save(createAppointmentRequest);
    }
}

И наконец у меня есть этот Контроллер class-

Встреча. java

@RestController
@RequestMapping("/api")
public class AppointmentController {

    @Autowired
    AppointmentService appointmentService;

    @GetMapping("/doctors/{doctorId}/appointments")
    public Page<Appointment> getAllAppointmentsByDoctorId(@PathVariable(value = "id") Long id, Pageable pageable){
        return appointmentService.getAllAppointmentByDoctorId(id, pageable);
    }


    @PostMapping("/insert/new/appointments")
    public Appointment createAppointment(@Valid Appointment createAppointmentRequest) {
        return appointmentService.createAppointment(createAppointmentRequest);
    }

}

Но всякий раз, когда я запускаю проект и выполняю POST-запрос на создание Встречи, используя упомянутое тело запроса, он показывает следующее Благодаря ответу -

enter image description here

Итак, мне нужно знать, в чем проблема в моем коде и как я могу создать встречу POST-запрос давая doctorId и PatientId , как я упоминал в запросе JSON RequestBody .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...