【发布时间】:2025-12-24 10:55:10
【问题描述】:
下面我展示了从使用表单到持久层的数据流。但是对于哪些对象应该在 MVC 的哪个层可用以及数据应该如何在 MVC 的不同层之间传输存在疑问。我正在使用 Spring,所以下面发布的代码是 Spring 框架的代码。
开始吧,我有一个 DTO(数据传输对象)PatientForm,它保存了用户输入的表单数据。
public class Patient {
private int id;
private String name;
private String medicineOne;
private String medicineTwo;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMedicineOne() {
return medicineOne;
}
public void setMedicineOne(String medicineOne) {
this.medicineOne = medicineOne;
}
public String getMedicineTwo() {
return medicineTwo;
}
public void setMedicineTwo(String medicineTwo) {
this.medicineTwo = medicineTwo;
}
}
PatientForm 被传递给控制器PatientController,不传输数据而是将表单传递给服务层PatientService。
@PostMapping("/patient/addpatient")
public ModelAndView addPatient(@ModelAttribute("patientform") PatientForm patient){
patientService.addPatient(patient);
return new ModelAndView("redirect:/");
}
在服务层 PatientService 中,数据从 DTO 到持久实体 Patient 的实际传输发生。
public void addPatient(com.hp.view.form.PatientForm patientForm){
String medicineOneName = patientForm.getMedicineOne();
Medicine medicineOne = medicineService.findByName(medicineOneName);
if(medicineOne == null){
medicineService.save(new Medicine(medicineOneName));
medicineOne = medicineService.findByName(medicineOneName);
}
String medicineTwoName = patientForm.getMedicineTwo();
Medicine medicineTwo = medicineService.findByName(medicineTwoName);
if(medicineTwo == null){
medicineService.save(new Medicine(medicineTwoName));
medicineTwo = medicineService.findByName(medicineTwoName);
}
List<Medicine> medicines = new ArrayList<>();
medicines.add(medicineOne);
medicines.add(medicineTwo);
Patient patient = new Patient();
patient.setName(patientForm.getName());
patient.setMedicine(medicines);
patientRepository.save(patient);
}
根据上述流程,这是我的问题:
是否应该
Controller layer或Service layer将数据从 DTO 传输到持久实体?如果在控制器中完成数据传输,则模型实体将在控制器层中声明。如果数据传输在服务层完成,则意味着 DTO 将在服务层声明。两者哪个更受欢迎?
在我的服务层中,我已经实例化了我的实体对象
Patient的实例。这会产生问题吗?我应该让 Spring contianer 管理我的实体 bean?
Patient patient = new Patient();
【问题讨论】:
标签: java spring-mvc model-view-controller persistence data-transfer-objects