在我的项目中,我在公司和location之间有一对多的映射。虽然添加位置我想要公司对象。 我有两个不同的公司和位置控制器
在公司控制器中:
addCompany
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addCompany(@ModelAttribute("company")
Company company, BindingResult result,Model model) {
companyService.addCompany(company);
return "companyPage";
}
updateCompany
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String updateCompany(@ModelAttribute("company")
Company company, BindingResult result,@RequestParam(value = "submitVal") String updateOrRestore
,Model model) {
if (updateOrRestore.equalsIgnoreCase("update")) {
companyService.updateCompany(company);
model.addAttribute("location", new Location());
} else if (updateOrRestore.equalsIgnoreCase("restore")) {
Company prevCompany = companyService.restoreCompany();
model.addAttribute("company", prevCompany);
model.addAttribute("location", new Location());
}
return "companyPage";
}
位置控制器:
addLocation
@RequestMapping(value="/addLocation", method = RequestMethod.POST )
public String addLocation(@ModelAttribute("location")
Location location,BindingResult reult, Model model){
logger.info("Location is added"+location);
//Here b4 adding location in db i want to set company obj
//location.setCompany(company);
locationService.addLocation(location);
}
如何在公司控制器操作中获取保存或更新的公司对象?
答案 0 :(得分:1)
在IF的帮助下从DB获取Company对象。 您必须在表单帖子中的隐藏输入框中保留此ID,并在控制器中执行,如下所示
@RequestMapping(value="/addLocation", method = RequestMethod.POST )
public String addLocation(@ModelAttribute("location")
Location location,BindingResult reult, Model model,@requestParam("cmpID") long ID){
//Company companyObj=get from DB with help of ID
//location.setCompany(companyObj);
locationService.addLocation(location);
return "yourview";
}