2013-05-08 57 views
0

我有两个表格:Company和Automotive。一家公司可以有许多汽车。 我无法正确持续使用汽车。公司从下拉菜单中选择“查看”页面。带休眠数据的Spring MVC数据保存错误

我的控制器

@RequestMapping("/") 
public String view(ModelMap model) { 
    Map<String, String> companyList = new HashMap<String, String>(); 
    List<Company> companies = companyService.listAllCompanies(); 
    for (Company company : companies) { 
     companyList.put(String.valueOf(company.getId()), company.getName()); 
    } 
    model.addAttribute("companies", companyList); 

    model.addAttribute("automotive", new Automotive()); 
    return "automotive/index"; 
} 

@RequestMapping("manage") 
public String manage(@ModelAttribute Automotive automotive, 
     BindingResult result, ModelMap model) { 
    model.addAttribute("automotive", automotive); 

    Map<String, String> companyList = new HashMap<String, String>(); 
    List<Company> companies = new ArrayList<Company>(); 
    for (Company company : companies) { 
     companyList.put(String.valueOf(company.getId()), company.getName()); 
    } 
    model.addAttribute("companies", companyList); 
    automotiveService.addAutomotive(automotive); 
    return "automotive/index"; 
} 

我查看

<form:form action="/Automotive/manage" modelAttribute="automotive"> 
    Name : <form:input path="name" /> 
    Description : <form:input path="description" /> 
    Type : <form:input path="type" /> 
    Company : <form:select path="company" items="${companies}" /> 
    <input type="submit" /> 
</form:form> 

Q1>按道理预期公司ID不会因为这里鉴于其一个id保存,但实际上同时节省它应该是一个对象型公司。我应该如何解决这个问题。我需要使用DTO还是有直接的方法?

Q2>我无法直接通过公司列表查看,而不是在控制器中创建新的地图?

回答

1

您可以使用公司的ID作为关键,然后使用转换器,它会自动将数据从表单转换为域对象。就像在这个代码:

public class CompanyIdToInstanceConverter implements Converter<String, Company> { 

    @Inject 
    private CompanyService _companyService; 

    @Override 
    public Company convert(final String companyIdStr) { 
     return _companyService.find(Long.valueOf(companyIdStr)); 
    } 

} 

而且在JSP:

<form:select path="company" items="${companies}" itemLabel="name" itemValue="id"/> 

您可能需要阅读更多有关类型转换,如果你还没有触及这个呢。它在Spring doc中有完美的描述(我找不到:http://static.springsource.org/spring/docs/3.0.x/reference/validation.html段落5.5)。

我希望它能帮助你。