我有一个可以分配给WorkOrder的用户下拉列表。用户到工作订单是一个一对多关系。问题是如何为用户ID分配NULL值?如果我不将其设置为NULL,则可以正常工作,并且可以从列表中分配任何名称。

如果我使用此代码并在我的jsp中选择NULL <form:option value="${null}" label="null" />,则会收到错误消息:

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: ""

这是我的工作单

    @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。整数可以为null。
我还向我的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);


}

07-24 09:49
查看更多