If your posting something like JSON data representing the User
class you can use the annotation @Valid
in conjunction with @RequestBody to trigger validation of annotations such as the @NotNull
you have on your age
property. Then with BindingResult
you can check if the entity/data has errors and handle accordingly.
@RestController
public UserController {
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> create(@Valid @RequestBody User user, BindingResult bindingResult) {
if(bindingResult.hasErrors()) {
// handle errors
}
else {
// entity/date is valid
}
}
}
I'd make sure your User
class also has the @Entity
annotation as well.
@Entity
public class User {
@NotNull
@Min(18)
private Integer age;
public Integer getAge() { return age; }
public setAge(Integer age) { this.age = age; }
}
You may want to set properties to output/log SQL so that you can see that the proper restraints are being added to the User table.
Hopefully that helps!