2017-01-16 76 views
1

我有一個用戶下拉列表,我可以分配給WorkOrder。用戶到WorkOrder是OneToMany關係。問題是如何將NULL值分配給用戶Id?如果我不將它設置爲NULL,它可以正常工作,我可以從列表中分配任何名稱。如何在我的下拉列表中將值設置爲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); 


} 

我的工作單,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> 

回答

0

原來在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); 


} 
相關問題