使用Hibernate Validator自动填充多选

时间:2013-07-04 09:42:17

标签: java hibernate spring-mvc hibernate-validator

我正在使用Hibernate Validator和Spring MVC,我有一个多选的问题(在ManyToMany关系中)。我的基类是Project。 Project包括以下字段:name(String),User(ManyToOne),regions(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:

@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;
        }
    });

在返回表单中,填写了字段“名称”ID,选择了用户,但区域multiselect 为空

更有趣的是,如果对象在数据库中保留,则在“编辑”表单中,多选正确填写

1 个答案:

答案 0 :(得分: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";        
}

还有其他想法吗?