我正在尝试为 CRUD Web 应用程序创建“更新”表单。与我的问题相关的类在 MySQL 数据库中以 1:N 方式相关。
我无法找到一个优雅的解决方案来将department参数转换为正确的类型。我可以使用表单的 jsp 构建一个丑陋的解决方法,但我想知道标准的 SpringMVC/Hibernate 解决方案是什么。
我有以下 Hibernate 实体类,Employee 和 Department,使用以下代码实现:
@Entity
@Table(name="employee")
public class Employee {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;
@JoinColumn(name = "ID_DEPT", referencedColumnName = "ID_DEPT")
@ManyToOne(optional = false)
private Department deptId;
...
}
更新是通过 jsp 文件中的 post 请求执行的,如下所示:
<form:hidden path="idEmployee" />
<div class="form-group">
<label for="deptid" class="col-md-3 control-label">Department</label>
<div class="col-md-9">
<form:input path="deptId" cssClass="form-control" />
</div>
</div>
....
post 请求不会为 deptId 提供正确的类型,从而引发类型不匹配错误。
saveEmployee 操作的 Controller 代码是:
@PostMapping("/saveEmployee")
public String saveDisciplina(@ModelAttribute("employee") Disciplina theDisciplina) {
return "redirect:/employee/list";
}
有关EmployeeDAO的相关代码是:
@Override
public void saveEmployee(Employee theEmployee) {
Session currentSession = sessionFactory.getCurrentSession();
currentSession.saveOrUpdate(theEmployee);
}
我应该在哪里以及如何正确处理 post 参数?
最佳答案
我认为你可能误解了连接实体的理解,因为java存储了实体的引用。当你更新它时,你必须在 hibernate 状态下找到它并引用它。
看一下这个示例,希望对您有所帮助:
https://www.callicoder.com/hibernate-spring-boot-jpa-one-to-many-mapping-example/
关于java - 如何处理1 :N Foreign Key for CRUD in Spring MVC/Hibernate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56245001/