我有一个可以分配给工作订单的用户下拉列表。其中 User 到 WorkOrder 是 OneToMany 关系。问题是如何将 NULL 值分配给用户 ID ?如果我不将其设置为 NULL,它会正常工作,并且我可以从列表中分配任何名称。
如果我使用此代码并选择 NULL <form:option value="${null}" label="null" />
在我的 jsp 中我收到错误:
Failed to convert property value of type java.lang.String to required type int for property user.id; nested exception is java.lang.NumberFormatException: For input string: ""
这是我的WorkorderDAOImpl
@Override
public void saveWorkOrder(WorkOrder theWorkOrder) {
// get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
User user = theWorkOrder.getUser();
System.out.println("workorder: " + theWorkOrder);
System.out.println("user: " + user);
//save/update the work order
currentSession.saveOrUpdate(theWorkOrder);
}
我的workorder-form.jsp我省略了一些标签
<form:errors path="workorder.*"/>
<form:errors path="user.*"/>
<form:form action="saveWorkOrder" modelAttribute="workorder" method="POST">
<!-- need to assotiate the data with workorder id -->
<form:hidden path="id"/>
<table>
<tbody>
<tr>
<td><label>User name:</label></td>
<td><form:input path="user.userName"/></td>
</tr>
<tr>
<td><label>User:</label></td>
<td><form:select path="user.id">
<form:option value="${null}" label="null" />
<form:options items="${users}"
itemLabel="userName" itemValue="id"
/>
</form:select>
最佳答案
事实证明,Java 中的 int
不能为 NULL
,因此将我的 id
从 int 更改为 Integer
。整数可以为空。
我还在 WorkOrderDAOImpl.java 中添加了一个 if
语句来检查 user.id 是否设置为 null。
这是我更新的代码。
@Override
public void saveWorkOrder(WorkOrder theWorkOrder) {
System.out.println(" \n Printing from WorkOrder : \n");
// get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
User user = theWorkOrder.getUser();
if (user.getId() == null) {
theWorkOrder.setUser(null);
}
//save/update the work order
currentSession.saveOrUpdate(theWorkOrder);
}
关于java - 如何将下拉列表中的值设置为 NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41682058/