Spring MVC with Hibernate Data Saving Error

懵懂的女人 提交于 2019-12-25 09:35:52

问题


I have two tables: Company and Automotive. A company can have many automotives. I am unable to persist an Automotive properly. Company is selected in View page from a drop down.

My Controller

@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";
}

My View

<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> Logically as expected Company id would not be saved since here in view its an id but actually while saving it should be an object of type company. How should I solve this. Do I need to use a DTO or is there any direct method?

Q2> Can't i pass Company list directly to view instead of creating a new Map in controller?


回答1:


You can use id of company as a key and then use converter which will automatically convert data from form into domain object. Just like in this code:

public class CompanyIdToInstanceConverter implements Converter<String, Company> {

    @Inject
    private CompanyService _companyService;

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

}

And in JSP:

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

You may need to read more about type conversion if you haven't touched this yet. It is perfectly described in Spring doc (I you couldn't find: http://static.springsource.org/spring/docs/3.0.x/reference/validation.html paragraph 5.5).

I hope it would help you.



来源:https://stackoverflow.com/questions/16447335/spring-mvc-with-hibernate-data-saving-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!