I have entity:
public class User{
@NotNull
private Integer age;
}
In Restcontroller:
@RestController
public UserController {
.....
}
I have BindingResult, but field age Spring doesn't validate. Can you tell me why?
Thanks for your answers.
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!
If needed you can specifiy default messages
@NotNull("message": "age: positive number value is required")
@Min(value=18, message="age: positive number, min 18 is required")
and please use dto's
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With