0

我正在将 Hibernate Validator 与 Spring MVC 一起使用,并且我有一个多选问题(在 ManyToMany 关系中)。我的基类是项目。项目有,除其他外,字段:名称(字符串),用户(ManyToOne),区域(ManyToMany)

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
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 已填写,用户被选中,但区域多选为

更有趣的是,如果对象以“编辑”形式存在于数据库中,则正确填写了多选。

4

1 回答 1

0

我发现的解决方案之一是加载区域的完整对象是“saveProject”操作:

if(bindingResult.hasErrors()) {

    System.out.println(project.getRegions().size());
    //Printed size of regions is identical with selected

    if (project.getRegions() != null) {
        List<Region> regionsTemp = new ArrayList<Region>();
        for (Region region1 : project.getRegions()) {
            Region region = Database.findById(region1.getId());
            regionsTemp.add(region);
        }
        project.setRegions(regionsTemp);
    }

    return "templates/project/form";        
}

还有其他想法吗?

于 2013-07-04T11:01:50.883 回答