无法将数据插入两个表spring mvc

时间:2017-05-04 09:09:22

标签: java spring hibernate jsp spring-mvc

我使用Spring mvc并面临将数据插入两个表的问题,我的目标是将数据从1个jsp(1个表单)插入2个表中 我有两张2桌:

1.Cars
  Id
  Name
  CityId(FK) 

2.City
  Id
  Name

这是我的控制者:

@RequestMapping(value="/CreateCar", method = RequestMethod.GET)
public ModelAndView getCreateCarPage(ModelMap model) throws ServletException, IOException {

    try {

        Car myCar = new Car();
        City city = new City();

        myCar.setCity(city);

        model.addAttribute("city", city);
        model.addAttribute("createCar", myCar);
    }       
    catch(Exception e) {
        e.printStackTrace();
    }

    return new ModelAndView("testForm");
}
@RequestMapping(value="/CreateCar", method = RequestMethod.POST)
public ModelAndView setCreateCarPage(ModelMap model,
                                     @ModelAttribute("createCar") Car createCar) throws SQLException, Exception {

    try {

        carService.createCar(createCar);

    }
    catch(Exception e) {
        e.printStackTrace();
    }

    return new ModelAndView("successProcess");
}

}

JSP:

<form:form modelAttribute="createCar" method="POST" commandName="createCar" action="/CreateCar" enctype="multipart/form-data">
<fieldset style="width:300px">          
    <table cellspacing="0" cellpadding="0" align="center">                              
    <tr>            
        <td>
            <label>Name of car</label>
            <form:input path="name" id="name"/>
        </td>       

        <td>
            <label>Name of city</label>
            <form:input path="city.name" />
        </td>                   
    </tr>
    <tr>
        <td><input class="btn btn-danger" type="submit" value="Inser New" style="width:100px;" /></td>          
    </tr>   
    </table>

</fieldset>

使用上述来源,只插入汽车成功名称但不能插入城市名称

日志按摩:

SqlExceptionHelper - Column 'city_id' cannot be null

如何解决此问题?非常感谢!

0 个答案:

没有答案