Spring 3 mvc @Valid注释不适用于List <Entity>属性

Ada*_*san 1 validation spring spring-mvc one-to-many

我想更新一个实体,该实体具有其他实体的一对多List集合.调用处理程序方法时,验证似乎不会在集合上运行.我已经阅读了文档,并搜索了stackoverflow,但没有找到任何有用的东西.

模型:

@Entity
public class Employee {
    @Id
    @GeneratedValue
    private int employeeId;
    @NotEmpty
    private String name;        
    @Min(value=18)
    private int age;        
    @OneToMany(mappedBy="parent",cascade=CascadeType.ALL)
    private List<Child> children;
//getters,setters
}
@Entity
public class Child {
    @Id
    @GeneratedValue
    private int childId;
    @Column(nullable=false)
    @NotNull
    @Size(min=1,message="Child's name must not be empty")
    private String childName;
    @Max(value=18)
    private Integer age;
    @ManyToOne
    @JoinColumn(name="employeeId")
    private Employee parent;
//getters,setters
}
Run Code Online (Sandbox Code Playgroud)

在控制器中:

    @RequestMapping(value = { "/edit/{id}" }, method = RequestMethod.POST)
    private String update(@PathVariable int id, ModelMap model, @Valid Employee employee, BindingResult result) {
        if (result.hasErrors()) {
            return "employee/edit";
        }
        employeeDao.merge(employee);
        return "redirect:../list";
    }
Run Code Online (Sandbox Code Playgroud)

验证适用于Employee bean的简单属性,但不适用于子列表中的元素.

怎么解决这个问题?

Dmi*_*kov 6

看起来你应该children@Valid注释装饰你的列表,如这里所述.

它应该看起来像这样:

@OneToMany(mappedBy="parent",cascade=CascadeType.ALL)
@Valid
private List<Child> children;
Run Code Online (Sandbox Code Playgroud)