When inserting a record using post request foreign key related reference record is not linking.
@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 Classes:
@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);
}
Database - Doctor Table: doctor_id doctor_name department 12345678 Dfirstname Dlastname ENT
POST Request - JSON Body { "patientName":"Pfirstname Plastname", "problem:"visibility problem - difficulty in low light", "doctor":{"doctorId":"12345678"} }
When I am sending this request the patient table doctor_id column is not being populated with the docortId.