我有两个模型,Patient
和 Study
。在 Study
模型中,我想使用 Patient
的 Id 作为外键。我的 Study
模型(没有 getter/setter)如下所示
@Entity
@Table(name = "Study")
public class Study {
@Id
@Column(name = "study_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@ManyToOne
@JoinColumn(name = "patient_id")
private Patient patient;
@NotNull
@Column(name = "description")
private String description;
@NotNull
@Column(name = "status")
private String status;
}
编辑:同时添加 Patient 类(没有 getter/setter)
@Entity
@Table(name="Patient")
public class Patient {
@Id
@Column(name="patient_id")
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@NotNull
@Column(name="name")
private String name;
@Column(name="sex")
private String sex;
@Column(name="date_of_birth")
private Date dateOfBirth;
}
我正在使用 Thymeleaf,我的 scheduleStudy.html
中的患者选择如下所示
<form method="POST" th:action="@{/scheduleStudy}" th:object="${study}">
<p>
Select Patient<select th:field="*{patient}"
required="required" class="form-control">
<option th:each="patient: ${patientList}" th:value="${patient.id}"
th:text="${patient.name}"></option>
</select>
</p>
表单正在成功加载,下拉列表中有患者列表。但是,当我在填写所有字段后提交表格时,我收到:
Validation failed for object='study'. Error count: 1 error on browser.
还有 Study
表单的 Controller 条目
@GetMapping("/scheduleStudy")
public String addSchedule(Model model) {
List<Patient> patientList = patientService.getPatients();
model.addAttribute("patientList", patientList);
model.addAttribute("study", new Study());
return "scheduleStudy";
}
@PostMapping("/scheduleStudy")
public void processAddSchedule(@ModelAttribute Study study) {
studyService.addStudy(study);
}
我刚开始使用 Thymeleaf,我认为我在 patient
字段中犯了一些错误。有人可以帮忙吗?
编辑 2:我已经更新了 POST 请求的方法,但是 patient
在 Controller 中仍然是 null。以前的浏览器错误当然消失了。
@RequestMapping(value = "/scheduleStudy", method = RequestMethod.POST)
public String processAddSchedule(Model model, @Valid @ModelAttribute("study") Study study,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
} else {
studyService.addStudy(study);
}
}
最佳答案
我正在处理类似的任务。据我所知,当您发布学习表格时,Thymeleaf 将所有字段作为参数发送到 POST 请求。它使用 toString() 将 Patient 对象转换为字符串。然后在组装 Study 对象时,它必须将 Patient 转换回 Object 形式。我通过向患者的标准转换服务注册 2 个转换器(toString 和 fromString)解决了这个问题。
关于java - 为什么这个与选择字段绑定(bind)的 Thymeleaf 表单不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51571933/