【问题标题】:Spring MVC with Hibernate Data Saving Error带有休眠数据保存错误的 Spring MVC
【发布时间】:2013-05-03 01:50:16
【问题描述】:

我有两个表:Company 和 Automotive。一家公司可以拥有许多汽车。 我无法正确地坚持汽车。从下拉列表中选择“查看”页面中的公司。

我的控制器

@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>我不能直接通过公司列表来查看而不是在控制器中创建新地图吗?

【问题讨论】:

    标签: java spring hibernate jakarta-ee spring-mvc


    【解决方案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 段)。

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2015-03-13
      • 1970-01-01
      • 2013-09-18
      • 1970-01-01
      • 2012-09-13
      • 1970-01-01
      • 2016-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多