java - 如何将下拉列表中的值设置为 NULL?

标签 java html hibernate jsp spring-mvc

我有一个可以分配给工作订单的用户下拉列表。其中 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/

相关文章:

java - ASTRewrite 用于 QuickFix : How to position the cursor?

html - 如何让我的 flexbox 与我的布局一起工作,我的侧边栏仍然卡在底部

html - 顶部和底部 : different transition

java - Jodatime Period 到 Jadira Usertype PersistentPeriodAsString。提供自定义格式?

java - 围绕中心坐标排序坐标 - JAVA

java - 正则表达式查询 MongoDB 性能问题

java - Hibernate加入具有父类(super class)属性的类

javascript - 如何使用 PHP 和 JAVASCRIPT 创建登录脚本?

Hibernate 检查两个不相关列是否相等

java - 从表和连接表中选择部分列 Criteria API