gpt4 book ai didi

java - Spring MVC 与 Hibernate 数据保存错误

转载 作者:行者123 更新时间:2023-12-01 14:36:27 25 4
gpt4 key购买 nike

我有两个表:Company 和 Automotive。一个公司可以拥有很多辆汽车。我无法正确保留汽车。在“查看”页面中从下拉列表中选择公司。

我的 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";
}

我的观点

<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> 我不能直接将公司列表传递给 View 而不是在 Controller 中创建新 map 吗?

最佳答案

您可以使用公司的 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 文档中对此进行了完美的描述(我找不到:http://static.springsource.org/spring/docs/3.0.x/reference/validation.html第5.5段)。

希望对你有帮助。

关于java - Spring MVC 与 Hibernate 数据保存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16447335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com