【问题标题】:How to set value to NULL in my dropdown list?如何在我的下拉列表中将值设置为 NULL?
【发布时间】:2017-05-31 15:01:44
【问题描述】:

我有一个可以分配给 WorkOrder 的用户下拉列表。其中 User 到 WorkOrder 是 OneToMany 关系。问题是如何将 NULL 值分配给 user Id ?如果我不将它设置为 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: ""

这是我的 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 html hibernate jsp spring-mvc


    【解决方案1】:

    原来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);
    
    
    } 
    

    【讨论】:

      猜你喜欢
      • 2020-01-24
      • 2021-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      相关资源
      最近更新 更多