2013-05-08 60 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)。

我希望它能幫助你。