我有两个实体:国家和联系人:
@Entity
@Table(name="countries")
@NamedQuery(name="Country.findAll", query="SELECT c FROM Country c")
public class Country implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String code;
private String name;
@OneToMany(mappedBy="countryBean")
private List<Contact> contacts;
//...
}
@Entity
@Table(name="contacts")
@NamedQuery(name="Contact.findAll", query="SELECT c FROM Contact c")
public class Contact implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String city;
private String street;
@ManyToOne
@JoinColumn(name="countries_id")
private Country countryBean;
//...
}
我需要添加新联系人并从数据库中选择现有国家。
我的控制器有一部分:
@RequestMapping(value="/contact/add", method=RequestMethod.GET)
public String contactAddGetPage(Model model) {
Contact contact = new Contact();
model.addAttribute("contact", contact);
List<Country> countries = countryManager.findAll();
model.addAttribute("countries", countries);
return "contactAdd";
}
@RequestMapping(value="/contact/add", method=RequestMethod.POST)
public String contactAddSave(
@Valid @ModelAttribute("contact") Contact contact, BindingResult result,
Model model, final RedirectAttributes redirectAttributes) {
if (result.hasErrors()) {
model.addAttribute("error", "error");
return "contactAdd";
}
contactManager.save(contact);
redirectAttributes.addFlashAttribute("message", "ok");
return "redirect:/contact";
}
以及使用 Spring Form 的“contactAdd.jsp”JSP:
<c:url var="sendToUrl" value="/contact/add" />
<form:form method="post" action="${sendToUrl}" commandName="contact">
<table>
<tr>
<td><form:label path="street">Street</form:label></td>
<td><form:input path="street"/></td>
<td><form:errors path="street"></form:errors></td>
</tr>
<tr>
<td><form:label path="city">City</form:label></td>
<td><form:input path="city"/></td>
<td><form:errors path="city"></form:errors></td>
</tr>
<tr>
<td><form:label path="countryBean">Country</form:label></td>
<td>
<form:select path="countryBean">
<form:options items="${countries}" itemValue="id" itemLabel="name" />
</form:select>
</td>
<td><form:errors path="countryBean"></form:errors></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Add" /></td>
</tr>
</table>
</form:form>
如果我在 www 浏览器中进入表单页面,它看起来还可以。有来自数据库的国家名称的 html 选择。
但是如果我点击“添加”按钮,我会得到“国家”表单选择:
无法将 java.lang.String 类型的属性值转换为属性 countryBean 所需的类型 com.example.test.entity.Country;嵌套异常是 java.lang.IllegalStateException:无法将类型 [java.lang.String] 的值转换为属性 countryBean 所需的类型 [com.example.test.entity.Country]:找不到匹配的编辑器或转换策略
我理解错误。我必须将国家转换为“国家”类。但是我该怎么做呢?