0
我使用Hibernate驗證與Spring MVC和我有一個問題與多選(在ManyToMany關係)。我的基類是Project。項目有(其中包括)字段:姓名(字符串),用戶(多對一),區(多對多)Autopopulate多選與Hibernate驗證
class Project {
.
private String name;
private User user;
private List<Region> regions
.
}
在控制器(POST行爲),我有:
public String saveProject(
@Valid Project project,
BindingResult bindingResult,
ModelMap model) {
//send regions, users etc. to model
//errors
if(bindingResult.hasErrors()) {
System.out.println(project.getRegions().size());
//Printed size of regions is identical with selected
return "templates/project/form";
}
//no errors, save to database etc.
}
InitBinder:
@InitBinder
public void initBinder (WebDataBinder binder)
{
StringTrimmerEditor stringtrimmer = new StringTrimmerEditor(true);
binder.registerCustomEditor(String.class, stringtrimmer);
binder.registerCustomEditor(List.class, "regions",new CustomCollectionEditor(List.class){
@Override
protected Object convertElement(Object element) {
Region region = new Region();
if (element != null) {
Integer id = Integer.valueOf(element.toString());
region.setId(id);
}
return region;
}
});
在回報表格中,字段'name'id填寫完畢,用戶被選中,但區域多選是空。
更有趣的是,如果對象仍然存在於數據庫中,那麼在'編輯'表單中,多選是正確填寫。