Java Spring Crudepository-如何按外键ID插入记录?
使用post请求插入记录时,外键相关的引用记录未链接Java Spring Crudepository-如何按外键ID插入记录?,java,spring-boot,spring-data-jpa,hibernate-mapping,Java,Spring Boot,Spring Data Jpa,Hibernate Mapping,使用post请求插入记录时,外键相关的引用记录未链接 @RestController @RequestMapping("auth") public class PatientController { @Autowired private PatientService patientService; @PostMapping(value = "patient/register", consumes = MediaType.APPLICATION_JSON_VALUE
@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> {
}
@RestController
@请求映射(“auth”)
公共类病人控制员{
@自动连线
私人病人服务;
@PostMapping(value=“patient/register”,consumes=MediaType.APPLICATION\u JSON\u value,products=MediaType.APPLICATION\u JSON\u value)
公共字符串注册患者(@RequestBody Patient Patient){
字符串响应=patientService.registerPatient(患者);
返回“{'result':“+response+”}”;
}
}
@服务
公营病人服务{
@自动连线
私人病人;私人病人;
公共字符串注册患者(患者){
patient=patientRepo.save(患者);
}
}
@存储库
公共接口PatientPository扩展了CrudePository{
}
实体类:
@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);
}
@实体
@表(name=“患者”)
公共类Patient实现java.io.Serializable{
@身份证
@GeneratedValue(策略=GenerationType.AUTO)
@列(name=“患者id”)
私家侦探;
@列(name=“patient_name”,长度=200)
私有字符串patientName;
@列(name=“problem”,长度=200)
私有字符串问题;
@manytone(fetch=FetchType.LAZY)
@JoinColumn(name=“doctor\u id”,nullable=false,insertable=false,updateable=false)
私家医生;
}
@实体
@表(name=“doctor”)
公共类Doctor实现java.io.Serializable{
@身份证
@GeneratedValue(策略=GenerationType.AUTO)
@列(name=“doctor\u id”)
私人内特博士;
@列(name=“doctor\u name”,长度=200)
私有字符串doctorName;
@列(name=“department”,长度=200)
私人弦乐部;
@OneToMany(fetch=FetchType.LAZY,mappedBy=“医生”)
私有集患者=新哈希集(0);
}
数据库-医生表:
医生id医生姓名科室
12345678 Dfirstname Dlastname ENT
请求后-JSON正文
{
“patientName”:“Pfirstname Plastname”,
“问题:”能见度问题-昏暗光线下的困难“,
“医生”:{“医生ID”:“12345678”}
}
当我发送此请求时,患者表医生id列未填充docortId。乍一看(由于未提供服务层),您必须从@JoinColumn中删除insertable=false和Updateable=false
@JoinColumn(name=“doctor\u id”,nullable=false,insertable=false,updateable=false)
将此更改为:
@JoinColumn(name=“doctor\u id”,nullable=false)
因为该指令不允许jpa插入/更新DOCTOR\u ID
列
此外,我更喜欢使用werappers而不是primitive类型,因为@Id将int更改为整数,正如这里建议的那样
另外,您似乎已经持久化了医生
(因为它已经分配了id),您应该首先选择医生到db,并用两端将患者添加到db:
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);
}
您还可以添加savePatient逻辑吗?您在配置中声明它既不可更新也不可插入,最后您没有在关系中级联任何更改。Hi@Nonika,我已经添加了save patient逻辑。Hi Nonika,在我的要求中,医生记录已经存在于数据库中。因此,当新患者将在Pati进行注册时JSON中将只提供ent详细信息医生Id(我在文章中还添加了控制器、服务和存储库类)
@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";
}