我有一个像这样的实体类Employee。它有一个对象部门(另一个实体)
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@NotNull
@NotEmpty
@Valid
private String name;
@DateTimeFormat(pattern="dd/MM/yyyy")
@Valid
private Date date;
private String cmt;
private String address;
private String position;
private Boolean matrimony = true;
@ManyToOne
@Valid
private Department department;
}
控制器,创建控制器显示编辑页面,并添加控制器解决添加请求:
@RequestMapping(value = "/employee/add", method = RequestMethod.POST)
public String add(@Validated @ModelAttribute(value = "employee") Employee employee) {
employeeRepository.save(employee);
return "redirect:./list";
}
@RequestMapping(value = "/employee/create")
public ModelAndView create(ModelMap mm) {
mm.addAttribute("action", "add");
mm.addAttribute("employee", new Employee());
mm.addAttribute("dao", new DepartmentDAO(departmentRepository));
return new ModelAndView("../jsp/employee/edit.jsp");
}
查看,是输入员工数据并提交添加方法的表格。
<form:form method="POST" action="${website_url}" commandName="employee">
<form:hidden path="id"></form:hidden>
<div class="form-group">
Name:
<form:input path="name" class="form-control"></form:input>
</div>
<div class="form-group">
Date of birth:
<form:input path="date" class="form-control"></form:input>
</div>
<div class="form-group">
ID card number:
<form:input path="cmt" class="form-control"></form:input>
</div>
<div class="form-group">
Address:
<form:input path="address" class="form-control"></form:input>
</div>
<div class="form-group">
Department:
<form:select path="department.id" class="form-control">
<% for(Department department : departmentDAO.departmentRepository.findAll()){%>
<form:option value="<%= department.getId() %>">
<%= department.getName() %>
</form:option>
<% } %>
</form:select>
</div>
<div class="form-group">
Position:
<form:select path="position" class="form-control">
<form:option value="Director">Director</form:option>
<form:option value="Department Leader">Department Leader</form:option>
<form:option value="Employee">Employee</form:option>
</form:select>
</div>
<div class="form-group form-inline">
Matrimony:
<form:checkbox path="matrimony" class="form-control"></form:checkbox>
</div>
<input type="submit" value="save" class="btn btn-primary form-control" />
</form:form>
我运行spring并正确加载编辑页面。但是我提交了表格,因为外键部门我收到了400 Bad请求。
答案 0 :(得分:0)
JPA很可能会抱怨你将一个分离的Department
实体传递给persist
。
您应该使用一种服务方法,该方法将调用employee.setDepartment(departmentDAO.findById(employee.getDepartment().getId()))
行,然后再调用employeeRepository.save(employee)
。
或者,您可以将cascade = MERGE
添加到@ManyToOne
并在控制器中添加类似的代码行,但这不会是安全的交易。