spring 3.2 mvcで複雑なオブジェクトを受け取る方法は?
以下の単純な例では、多対 1 の関係を持つ 2 つのモデル クラスがあります。新しい Employee オブジェクトを追加するとき、html select を使用して部門を選択したいと思います。
新しい従業員を追加するために投稿すると、次のエラーが表示されます。
タイプ java.lang.String のプロパティ値をプロパティ department の必要なタイプ hu.pikk.model.Department に変換できませんでした。ネストされた例外は java.lang.IllegalStateException です: タイプ [java.lang.String] の値をプロパティ部門の必要なタイプ [hu.pikk.model.Department] に変換できません: 一致するエディターまたは変換戦略が見つかりません
エディターまたは変換戦略をどのように実装すればよいですか? 注意すべきベストプラクティスや落とし穴はありますか?
spring mvc のドキュメント、いくつかの記事、stackoverflow の質問を読んだことがありますが、正直なところ、それらは少し混乱し、多くの場合短すぎて手に負えません。
モデル:
@Entity
public class Employee {
@Id
@GeneratedValue
private int employeeId;
@NotEmpty
private String name;
@ManyToOne
@JoinColumn(name="department_id")
private Department department;
//getters,setters
}
@Entity
public class Department {
@Id
@GeneratedValue
private int departmentId;
@Column
private String departmentName;
@OneToMany
@JoinColumn(name = "department_id")
private List<Employee> employees;
//getters,setters
}
私のコントローラークラスでは:
@RequestMapping(value = "/add", method = RequestMethod.GET)
private String addNew(ModelMap model) {
Employee newEmployee = new Employee();
model.addAttribute("employee", newEmployee);
model.addAttribute("departments", departmentDao.getAllDepartments());
return "employee/add";
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
private String addNewHandle(@Valid Employee employee, BindingResult bindingResult, ModelMap model, RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute("departments", departmentDao.getAllDepartments());
return "employee/add";
}
employeeDao.persist(employee);
redirectAttributes.addFlashAttribute("added_employee", employee.getName());
redirectAttributes.addFlashAttribute("message", "employee added...");
return "redirect:list";
}
add.jsp:
<f:form commandName="employee" action="${pageContext.request.contextPath}/employee/add" method="POST">
<table>
<tr>
<td><f:label path="name">Name:</f:label></td>
<td><f:input path="name" /></td>
<td><f:errors path="name" class="error" /></td>
</tr>
<tr>
<td><f:label path="department">Department:</f:label></td>
<td><f:select path="department">
<f:option value="${null}" label="NO DEPARTMENT" />
<f:options items="${departments}" itemLabel="departmentName" itemValue="departmentId" />
</f:select></td>
<td><f:errors path="department" class="error" /></td>
</tr>
</table>
<input type="submit" value="Add Employee">
</f:form>