Java 多对多关系休眠的不正确实现?

Java 多对多关系休眠的不正确实现?,java,hibernate,spring-boot,Java,Hibernate,Spring Boot,如果你能帮助我,我将不胜感激。 我有几个Postgress表格: 医生 患者 医生/患者 当我尝试将患者添加到医生表(多对多关系)时,我的doctor\u patient表只包含最新记录。我真不明白为什么(: 以下是我的实现: 患者控制员: @PostMapping("/users/{userId}/patients") public ResponseEntity<?> addPatient(@PathVariable(value = "userId") final Long us

如果你能帮助我,我将不胜感激。 我有几个Postgress表格:

  • 医生
  • 患者
  • 医生/患者
  • 当我尝试将患者添加到医生表(多对多关系)时,我的doctor\u patient表只包含最新记录。我真不明白为什么(:

    以下是我的实现:

    患者控制员:

     @PostMapping("/users/{userId}/patients")
    public ResponseEntity<?> addPatient(@PathVariable(value = "userId") final Long userId,
                                        @Valid @RequestBody final Patient patient) {
    
        if (patientRepository.existsByPatientEmail(patient.getPatientEmail())) {
            return new ResponseEntity<>(new ApiResponse(false, "Patient email is already taken!"),
                    HttpStatus.BAD_REQUEST);
        }
    
        if (patientRepository.existsByPatientCellPhone(patient.getPatientCellPhone())) {
            return new ResponseEntity<>(new ApiResponse(false, "Cell phone already in use!"),
                    HttpStatus.BAD_REQUEST);
        }
    
        if(!userRepository.existsById(userId)) {
            return new ResponseEntity<>(new ApiResponse(false, "User by id is not found!"),
                    HttpStatus.NOT_FOUND);
        }
    
        userRepository.getById(userId).map(item -> {
            final Set<Patient> patients = new HashSet<>();
            patients.add(patient);
            item.setPatients(patients);
            userRepository.save(item);
            return item;
        }).orElseThrow(() -> new UsernameNotFoundException("Following user is not found!"));
    
        return new ResponseEntity<>(new ApiResponse(true, "Patient created successfully"), HttpStatus.OK);
    }
    
    @ManyToMany(mappedBy = "patients")
    private Set<Doctor> doctors = new HashSet<>();
    
    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name = "doctor_patients",
            joinColumns = { @JoinColumn(name = "doctor_id", referencedColumnName = "id") },
            inverseJoinColumns = { @JoinColumn(name = "patient_id", referencedColumnName = "id")})
    private Set<Patient> patients = new HashSet<>();
    
    @PostMapping(“/users/{userId}/patients”)
    public ResponseEntity addPatient(@PathVariable(value=“userId”)最终长用户标识,
    @有效@RequestBody(最终患者){
    if(patientRepository.existsByPatientEmail(patient.getPatientMail())){
    return new ResponseEntity(新的ApiResponse(错误,“患者电子邮件已被接收!”),
    HttpStatus.BAD_请求);
    }
    if(patientPository.existsByPatientPhone(patient.getPatientCellPhone())){
    return new ResponseEntity(新的ApiResponse(false,“手机已在使用!”),
    HttpStatus.BAD_请求);
    }
    如果(!userRepository.existsById(userId)){
    返回新的ResponseEntity(新的ApiResponse(false,“未找到id用户!”),
    HttpStatus。未找到);
    }
    userRepository.getById(userId).map(项->{
    最终集患者=新HashSet();
    患者。添加(患者);
    项目.病人(病人);
    userRepository.save(项目);
    退货项目;
    }).orelsetrow(()->new UsernameNotFoundException(“未找到以下用户”);
    返回新的ResponseEntity(新的ApiResponse(true,“患者创建成功”),HttpStatus.OK;
    }
    
    患者实体:

     @PostMapping("/users/{userId}/patients")
    public ResponseEntity<?> addPatient(@PathVariable(value = "userId") final Long userId,
                                        @Valid @RequestBody final Patient patient) {
    
        if (patientRepository.existsByPatientEmail(patient.getPatientEmail())) {
            return new ResponseEntity<>(new ApiResponse(false, "Patient email is already taken!"),
                    HttpStatus.BAD_REQUEST);
        }
    
        if (patientRepository.existsByPatientCellPhone(patient.getPatientCellPhone())) {
            return new ResponseEntity<>(new ApiResponse(false, "Cell phone already in use!"),
                    HttpStatus.BAD_REQUEST);
        }
    
        if(!userRepository.existsById(userId)) {
            return new ResponseEntity<>(new ApiResponse(false, "User by id is not found!"),
                    HttpStatus.NOT_FOUND);
        }
    
        userRepository.getById(userId).map(item -> {
            final Set<Patient> patients = new HashSet<>();
            patients.add(patient);
            item.setPatients(patients);
            userRepository.save(item);
            return item;
        }).orElseThrow(() -> new UsernameNotFoundException("Following user is not found!"));
    
        return new ResponseEntity<>(new ApiResponse(true, "Patient created successfully"), HttpStatus.OK);
    }
    
    @ManyToMany(mappedBy = "patients")
    private Set<Doctor> doctors = new HashSet<>();
    
    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name = "doctor_patients",
            joinColumns = { @JoinColumn(name = "doctor_id", referencedColumnName = "id") },
            inverseJoinColumns = { @JoinColumn(name = "patient_id", referencedColumnName = "id")})
    private Set<Patient> patients = new HashSet<>();
    
    @ManyToMany(mappedBy=“患者”)
    私有集医生=新HashSet();
    
    医生实体:

     @PostMapping("/users/{userId}/patients")
    public ResponseEntity<?> addPatient(@PathVariable(value = "userId") final Long userId,
                                        @Valid @RequestBody final Patient patient) {
    
        if (patientRepository.existsByPatientEmail(patient.getPatientEmail())) {
            return new ResponseEntity<>(new ApiResponse(false, "Patient email is already taken!"),
                    HttpStatus.BAD_REQUEST);
        }
    
        if (patientRepository.existsByPatientCellPhone(patient.getPatientCellPhone())) {
            return new ResponseEntity<>(new ApiResponse(false, "Cell phone already in use!"),
                    HttpStatus.BAD_REQUEST);
        }
    
        if(!userRepository.existsById(userId)) {
            return new ResponseEntity<>(new ApiResponse(false, "User by id is not found!"),
                    HttpStatus.NOT_FOUND);
        }
    
        userRepository.getById(userId).map(item -> {
            final Set<Patient> patients = new HashSet<>();
            patients.add(patient);
            item.setPatients(patients);
            userRepository.save(item);
            return item;
        }).orElseThrow(() -> new UsernameNotFoundException("Following user is not found!"));
    
        return new ResponseEntity<>(new ApiResponse(true, "Patient created successfully"), HttpStatus.OK);
    }
    
    @ManyToMany(mappedBy = "patients")
    private Set<Doctor> doctors = new HashSet<>();
    
    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name = "doctor_patients",
            joinColumns = { @JoinColumn(name = "doctor_id", referencedColumnName = "id") },
            inverseJoinColumns = { @JoinColumn(name = "patient_id", referencedColumnName = "id")})
    private Set<Patient> patients = new HashSet<>();
    
    @ManyToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL)
    @JoinTable(name=“医生\患者”,
    joinColumns={@JoinColumn(name=“doctor\u id”,referencedColumnName=“id”)},
    inverseJoinColumns={@JoinColumn(name=“patient\u id”,referencedColumnName=“id”)}
    private Set patients=new HashSet();
    
    患者表:

     @PostMapping("/users/{userId}/patients")
    public ResponseEntity<?> addPatient(@PathVariable(value = "userId") final Long userId,
                                        @Valid @RequestBody final Patient patient) {
    
        if (patientRepository.existsByPatientEmail(patient.getPatientEmail())) {
            return new ResponseEntity<>(new ApiResponse(false, "Patient email is already taken!"),
                    HttpStatus.BAD_REQUEST);
        }
    
        if (patientRepository.existsByPatientCellPhone(patient.getPatientCellPhone())) {
            return new ResponseEntity<>(new ApiResponse(false, "Cell phone already in use!"),
                    HttpStatus.BAD_REQUEST);
        }
    
        if(!userRepository.existsById(userId)) {
            return new ResponseEntity<>(new ApiResponse(false, "User by id is not found!"),
                    HttpStatus.NOT_FOUND);
        }
    
        userRepository.getById(userId).map(item -> {
            final Set<Patient> patients = new HashSet<>();
            patients.add(patient);
            item.setPatients(patients);
            userRepository.save(item);
            return item;
        }).orElseThrow(() -> new UsernameNotFoundException("Following user is not found!"));
    
        return new ResponseEntity<>(new ApiResponse(true, "Patient created successfully"), HttpStatus.OK);
    }
    
    @ManyToMany(mappedBy = "patients")
    private Set<Doctor> doctors = new HashSet<>();
    
    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name = "doctor_patients",
            joinColumns = { @JoinColumn(name = "doctor_id", referencedColumnName = "id") },
            inverseJoinColumns = { @JoinColumn(name = "patient_id", referencedColumnName = "id")})
    private Set<Patient> patients = new HashSet<>();
    

    医生表:

     @PostMapping("/users/{userId}/patients")
    public ResponseEntity<?> addPatient(@PathVariable(value = "userId") final Long userId,
                                        @Valid @RequestBody final Patient patient) {
    
        if (patientRepository.existsByPatientEmail(patient.getPatientEmail())) {
            return new ResponseEntity<>(new ApiResponse(false, "Patient email is already taken!"),
                    HttpStatus.BAD_REQUEST);
        }
    
        if (patientRepository.existsByPatientCellPhone(patient.getPatientCellPhone())) {
            return new ResponseEntity<>(new ApiResponse(false, "Cell phone already in use!"),
                    HttpStatus.BAD_REQUEST);
        }
    
        if(!userRepository.existsById(userId)) {
            return new ResponseEntity<>(new ApiResponse(false, "User by id is not found!"),
                    HttpStatus.NOT_FOUND);
        }
    
        userRepository.getById(userId).map(item -> {
            final Set<Patient> patients = new HashSet<>();
            patients.add(patient);
            item.setPatients(patients);
            userRepository.save(item);
            return item;
        }).orElseThrow(() -> new UsernameNotFoundException("Following user is not found!"));
    
        return new ResponseEntity<>(new ApiResponse(true, "Patient created successfully"), HttpStatus.OK);
    }
    
    @ManyToMany(mappedBy = "patients")
    private Set<Doctor> doctors = new HashSet<>();
    
    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name = "doctor_patients",
            joinColumns = { @JoinColumn(name = "doctor_id", referencedColumnName = "id") },
            inverseJoinColumns = { @JoinColumn(name = "patient_id", referencedColumnName = "id")})
    private Set<Patient> patients = new HashSet<>();
    

    final Set patients=new HashSet();
    患者。添加(患者);
    项目.病人(病人);
    userRepository.save(项目);
    退货项目;
    

    代码的这一部分有一个错误。您可能想获取患者列表并添加一个新的患者列表,但每次都只是创建一个新的列表。此外,您声明存在多对多,但不允许将现有用户添加到其他医生。

    @PostMapping(“/users/{userId}/patients”)public ResponseEntity addPatient(@PathVariable(value=“userId”)final Long userId,@Valid@RequestBody final Patient Patient){
    感谢您的回答。我正在尝试通过Id(通过request param提供)查找医生,并将新患者分配给该医生(也通过RequestBody提供).但是什么也没发生((我真的不知道如何解决这个问题。也许我应该通过id找到医生,检索患者名单并更新这些名单?非常感谢!!!!!我节省了我的时间!!!!我已经更改了代码,根据旅游建议,现在它可以正常工作了!!!!