我有一个带有一些绑定到表单的简单属性的对象。问题是:这个对象还有一个对象Map,我想绑定到同一个表单。
对象是"事件","捐赠"和#34; Donor",定义如下:
// each event has a map of donations. the map key is the id of the donor
@Entity
public class Event {
@Column
private name;
// the key for this collection is the id of the donor
@OneToMany(mappedBy="event")
@MapKey(name="donor")
private Map<Integer,Donation> donations;
}
// each donation is for one event, has properties 'amount' and 'donor'
@Entity
public class Donation {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="ID", nullable = false)
private Integer id;
@ManyToOne
@JoinColumn(name="EVENT_ID")
private Event event;
@Column
private Double amount;
@ManyToOne
@JoinColumn(name="DONOR_ID")
private Donor donor;
}
// the donors are set elsewhere in the application
@Entity
public class Donor {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="ID", nullable = false)
private Integer id;
@Column
private String name;
}
我的JSP中的相关代码是:
<form:form name="form" method="post" commandName="event">
Name: <form:input path="name"/><br/>
Donations:<br/>
<c:forEach var="donation" items="${event.donations}">
${donation.value.donor.name}: <input name="donations[${donation.key}]" value="${donation.value.amount}" /><br/>
</c:forEach>
</form:form>
最后,表单提交以下控制器方法:
@RequestMapping(value="/{id}", method=RequestMethod.POST)
public String saveEvent(@Valid @ModelAttribute Event event, BindingResult result, Model model) {
// save event here
}
表单显示正确,但保存时出现以下错误:
Failed to convert property value of type java.lang.String to required type java.lang.Integer for property null; nested exception is java.lang.NumberFormatException: For input string: "myclasses.Donor@7cabee72"
从错误消息中我假设需要一个属性编辑器。我已经为简单的情况创建了属性编辑器,但在这里我很难过。
当集合是主对象的属性并且集合中的每个项目都有两个属性(金额和捐赠者)时,绑定对象集合的正确方法是什么?