Seems like you should decorate your children
list with @Valid
annotation, as described here.
It should look something like this:
@OneToMany(mappedBy="parent",cascade=CascadeType.ALL)
@Valid
private List<Child> children;
Question
I want to update an entity, which has a one-to-many List collection of other entity. When the handler method gets called, the validation doesn't seem to run on the collection. I've read the documentation, and searched stackoverflow, but did not find anything useful.
Model:
@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
}
In the controller:
@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";
}
The validation works for the simple properties of the Employee bean, but not for the elements in the children list.
How can this be fixed?
Solution
Seems like you should decorate your children
list with @Valid
annotation, as described here.
It should look something like this:
@OneToMany(mappedBy="parent",cascade=CascadeType.ALL)
@Valid
private List<Child> children;